Programs & Examples On #Immutability

Immutability is the inability to modify data after it has been created. Modifications are instead made by copying the data. A property of immutable data is that it is *referentially transparent*.

Java Immutable Collections

I believe the point here is that even if a collection is Unmodifiable, that does not ensure that it cannot change. Take for example a collection that evicts elements if they are too old. Unmodifiable just means that the object holding the reference cannot change it, not that it cannot change. A true example of this is Collections.unmodifiableList method. It returns an unmodifiable view of a List. The the List reference that was passed into this method is still modifiable and so the list can be modified by any holder of the reference that was passed. This can result in ConcurrentModificationExceptions and other bad things.

Immutable, mean that in no way can the collection be changed.

Second question: An Immutable collection does not mean that the objects contained in the collection will not change, just that collection will not change in the number and composition of objects that it holds. In other words, the collection's list of references will not change. That does not mean that the internals of the object being referenced cannot change.

Remove specific characters from a string in Python

Even the below approach works

line = "a,b,c,d,e"
alpha = list(line)
        while ',' in alpha:
            alpha.remove(',')
finalString = ''.join(alpha)
print(finalString)

output: abcde

Why .NET String is immutable?

Imagine you pass a mutable string to a function but don't expect it to be changed. Then what if the function changes that string? In C++, for instance, you could simply do call-by-value (difference between std::string and std::string& parameter), but in C# it's all about references so if you passed mutable strings around every function could change it and trigger unexpected side effects.

This is just one of various reasons. Performance is another one (interned strings, for example).

Replace Multiple String Elements in C#

There is one thing that may be optimized in the suggested solutions. Having many calls to Replace() makes the code to do multiple passes over the same string. With very long strings the solutions may be slow because of CPU cache capacity misses. May be one should consider replacing multiple strings in a single pass.

Set System.Drawing.Color values

You could do:

Color c = Color.FromArgb(red, green, blue); //red, green and blue are integer variables containing red, green and blue components

Correct way to push into state array

React-Native

if u also want ur UI (ie. ur flatList) to be up to date, use PrevState: in the example below if user clicks on the button , it is going to add a new object to the list( both in the model and UI)

data: ['shopping','reading'] // declared in constructor
onPress={() => {this.setState((prevState, props) => {
return {data: [new obj].concat(prevState.data) };
})}}. 

Why are exclamation marks used in Ruby methods?

It is most accurate to say that methods with a Bang! are the more dangerous or surprising version. There are many methods that mutate without a Bang such as .destroy and in general methods only have bangs where a safer alternative exists in the core lib.

For instance, on Array we have .compact and .compact!, both methods mutate the array, but .compact! returns nil instead of self if there are no nil's in the array, which is more surprising than just returning self.

The only non-mutating method I've found with a bang is Kernel's .exit! which is more surprising than .exit because you cannot catch SystemExit while the process is closing.

Rails and ActiveRecord continues this trend in that it uses bang for more 'surprising' effects like .create! which raises errors on failure.

String is immutable. What exactly is the meaning?

Before proceeding further with the fuss of immutability, let's just take a look into the String class and its functionality a little before coming to any conclusion.

This is how String works:

String str = "knowledge";

This, as usual, creates a string containing "knowledge" and assigns it a reference str. Simple enough? Lets perform some more functions:

 String s = str;     // assigns a new reference to the same string "knowledge"

Lets see how the below statement works:

  str = str.concat(" base");

This appends a string " base" to str. But wait, how is this possible, since String objects are immutable? Well to your surprise, it is.

When the above statement is executed, the VM takes the value of String str, i.e. "knowledge" and appends " base", giving us the value "knowledge base". Now, since Strings are immutable, the VM can't assign this value to str, so it creates a new String object, gives it a value "knowledge base", and gives it a reference str.

An important point to note here is that, while the String object is immutable, its reference variable is not. So that's why, in the above example, the reference was made to refer to a newly formed String object.

At this point in the example above, we have two String objects: the first one we created with value "knowledge", pointed to by s, and the second one "knowledge base", pointed to by str. But, technically, we have three String objects, the third one being the literal "base" in the concat statement.

Important Facts about String and Memory usage

What if we didn't have another reference s to "knowledge"? We would have lost that String. However, it still would have existed, but would be considered lost due to having no references. Look at one more example below

String s1 = "java";
s1.concat(" rules");
System.out.println("s1 refers to "+s1);  // Yes, s1 still refers to "java"

What's happening:

  1. The first line is pretty straightforward: create a new String "java" and refer s1 to it.
  2. Next, the VM creates another new String "java rules", but nothing refers to it. So, the second String is instantly lost. We can't reach it.

The reference variable s1 still refers to the original String "java".

Almost every method, applied to a String object in order to modify it, creates new String object. So, where do these String objects go? Well, these exist in memory, and one of the key goals of any programming language is to make efficient use of memory.

As applications grow, it's very common for String literals to occupy large area of memory, which can even cause redundancy. So, in order to make Java more efficient, the JVM sets aside a special area of memory called the "String constant pool".

When the compiler sees a String literal, it looks for the String in the pool. If a match is found, the reference to the new literal is directed to the existing String and no new String object is created. The existing String simply has one more reference. Here comes the point of making String objects immutable:

In the String constant pool, a String object is likely to have one or many references. If several references point to same String without even knowing it, it would be bad if one of the references modified that String value. That's why String objects are immutable.

Well, now you could say, what if someone overrides the functionality of String class? That's the reason that the String class is marked final so that nobody can override the behavior of its methods.

Const in JavaScript: when to use it and is it necessary?

To integrate the previous answers, there's an obvious advantage in declaring constant variables, apart from the performance reason: if you accidentally try to change or re-declare them in the code, the program will respectively not change the value or throw an error.

For example, compare:

// Will output 'SECRET'

const x = 'SECRET'
if (x = 'ANOTHER_SECRET') {  // Warning! assigning a value variable in an if condition
    console.log (x)
}

with:

// Will output 'ANOTHER_SECRET'

var y = 'SECRET'
if (y = 'ANOTHER_SECRET') { 
    console.log (y)
}

or

// Will throw TypeError: const 'x' has already been declared

const x = "SECRET"

/*  complex code */

var x = 0

with

// Will reassign y and cause trouble

var y = "SECRET"

/*  complex code */

var y = 0

Immutable array in Java

While it's true that Collections.unmodifiableList() works, sometimes you may have a large library having methods already defined to return arrays (e.g. String[]). To prevent breaking them, you can actually define auxiliary arrays that will store the values:

public class Test {
    private final String[] original;
    private final String[] auxiliary;
    /** constructor */
    public Test(String[] _values) {
        original = new String[_values.length];
        // Pre-allocated array.
        auxiliary = new String[_values.length];
        System.arraycopy(_values, 0, original, 0, _values.length);
    }
    /** Get array values. */
    public String[] getValues() {
        // No need to call clone() - we pre-allocated auxiliary.
        System.arraycopy(original, 0, auxiliary, 0, original.length);
        return auxiliary;
    }
}

To test:

    Test test = new Test(new String[]{"a", "b", "C"});
    System.out.println(Arrays.asList(test.getValues()));
    String[] values = test.getValues();
    values[0] = "foobar";
    // At this point, "foobar" exist in "auxiliary" but since we are 
    // copying "original" to "auxiliary" for each call, the next line
    // will print the original values "a", "b", "c".
    System.out.println(Arrays.asList(test.getValues()));

Not perfect, but at least you have "pseudo immutable arrays" (from the class perspective) and this will not break related code.

How do I delete specific characters from a particular String in Java?

Use:

String str = "whatever";
str = str.replaceAll("[,.]", "");

replaceAll takes a regular expression. This:

[,.]

...looks for each comma and/or period.

Immutable vs Mutable types

A mutable object has to have at least a method able to mutate the object. For example, the list object has the append method, which will actually mutate the object:

>>> a = [1,2,3]
>>> a.append('hello') # `a` has mutated but is still the same object
>>> a
[1, 2, 3, 'hello']

but the class float has no method to mutate a float object. You can do:

>>> b = 5.0 
>>> b = b + 0.1
>>> b
5.1

but the = operand is not a method. It just make a bind between the variable and whatever is to the right of it, nothing else. It never changes or creates objects. It is a declaration of what the variable will point to, since now on.

When you do b = b + 0.1 the = operand binds the variable to a new float, wich is created with te result of 5 + 0.1.

When you assign a variable to an existent object, mutable or not, the = operand binds the variable to that object. And nothing more happens

In either case, the = just make the bind. It doesn't change or create objects.

When you do a = 1.0, the = operand is not wich create the float, but the 1.0 part of the line. Actually when you write 1.0 it is a shorthand for float(1.0) a constructor call returning a float object. (That is the reason why if you type 1.0 and press enter you get the "echo" 1.0 printed below; that is the return value of the constructor function you called)

Now, if b is a float and you assign a = b, both variables are pointing to the same object, but actually the variables can't comunicate betweem themselves, because the object is inmutable, and if you do b += 1, now b point to a new object, and a is still pointing to the oldone and cannot know what b is pointing to.

but if c is, let's say, a list, and you assign a = c, now a and c can "comunicate", because list is mutable, and if you do c.append('msg'), then just checking a you get the message.

(By the way, every object has an unique id number asociated to, wich you can get with id(x). So you can check if an object is the same or not checking if its unique id has changed.)

Aren't Python strings immutable? Then why does a + " " + b work?

a = 'dog'
address = id(a)
print(id(a))

a = a + 'cat'
print(id(a))      #Address changes

import ctypes
ctypes.cast(address, ctypes.py_object).value    #value at old address is intact

Enums in Javascript with ES6

You could use ES6 Map

const colors = new Map([
  ['RED', 'red'],
  ['BLUE', 'blue'],
  ['GREEN', 'green']
]);

console.log(colors.get('RED'));

What is meant by immutable?

Objects which are immutable can not have their state changed after they have been created.

There are three main reasons to use immutable objects whenever you can, all of which will help to reduce the number of bugs you introduce in your code:

  • It is much easier to reason about how your program works when you know that an object's state cannot be changed by another method
  • Immutable objects are automatically thread safe (assuming they are published safely) so will never be the cause of those hard-to-pin-down multithreading bugs
  • Immutable objects will always have the same Hash code, so they can be used as the keys in a HashMap (or similar). If the hash code of an element in a hash table was to change, the table entry would then effectively be lost, since attempts to find it in the table would end up looking in the wrong place. This is the main reason that String objects are immutable - they are frequently used as HashMap keys.

There are also some other optimisations you might be able to make in code when you know that the state of an object is immutable - caching the calculated hash, for example - but these are optimisations and therefore not nearly so interesting.

What is difference between mutable and immutable String in java

In Java, all strings are immutable. When you are trying to modify a String, what you are really doing is creating a new one. However, when you use a StringBuilder, you are actually modifying the contents, instead of creating a new one.

How to give spacing between buttons using bootstrap

Use btn-primary-spacing class for all buttons remove margin-left class

Example :

<button type="button" class="btn btn-primary btn-color btn-bg-color btn-sm col-xs-2 btn-primary-spacing">
  <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> ADD PACKET
</button>

CSS will be like :

.btn-primary-spacing 
{
margin-right: 5px;
margin-bottom: 5px !important;
}

Can someone give an example of cosine similarity, in a very simple, graphical way?

This Python code is my quick and dirty attempt to implement the algorithm:

import math
from collections import Counter

def build_vector(iterable1, iterable2):
    counter1 = Counter(iterable1)
    counter2 = Counter(iterable2)
    all_items = set(counter1.keys()).union(set(counter2.keys()))
    vector1 = [counter1[k] for k in all_items]
    vector2 = [counter2[k] for k in all_items]
    return vector1, vector2

def cosim(v1, v2):
    dot_product = sum(n1 * n2 for n1, n2 in zip(v1, v2) )
    magnitude1 = math.sqrt(sum(n ** 2 for n in v1))
    magnitude2 = math.sqrt(sum(n ** 2 for n in v2))
    return dot_product / (magnitude1 * magnitude2)


l1 = "Julie loves me more than Linda loves me".split()
l2 = "Jane likes me more than Julie loves me or".split()


v1, v2 = build_vector(l1, l2)
print(cosim(v1, v2))

Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook

A solution I came up with is to use a vis.js instance in an iframe. This shows an interactive 3D plot inside a notebook, which still works in nbviewer. The visjs code is borrowed from the example code on the 3D graph page

A small notebook to illustrate this: demo

The code itself:

from IPython.core.display import display, HTML
import json

def plot3D(X, Y, Z, height=600, xlabel = "X", ylabel = "Y", zlabel = "Z", initialCamera = None):

    options = {
        "width": "100%",
        "style": "surface",
        "showPerspective": True,
        "showGrid": True,
        "showShadow": False,
        "keepAspectRatio": True,
        "height": str(height) + "px"
    }

    if initialCamera:
        options["cameraPosition"] = initialCamera

    data = [ {"x": X[y,x], "y": Y[y,x], "z": Z[y,x]} for y in range(X.shape[0]) for x in range(X.shape[1]) ]
    visCode = r"""
       <link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css" type="text/css" rel="stylesheet" />
       <script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
       <div id="pos" style="top:0px;left:0px;position:absolute;"></div>
       <div id="visualization"></div>
       <script type="text/javascript">
        var data = new vis.DataSet();
        data.add(""" + json.dumps(data) + """);
        var options = """ + json.dumps(options) + """;
        var container = document.getElementById("visualization");
        var graph3d = new vis.Graph3d(container, data, options);
        graph3d.on("cameraPositionChange", function(evt)
        {
            elem = document.getElementById("pos");
            elem.innerHTML = "H: " + evt.horizontal + "<br>V: " + evt.vertical + "<br>D: " + evt.distance;
        });
       </script>
    """
    htmlCode = "<iframe srcdoc='"+visCode+"' width='100%' height='" + str(height) + "px' style='border:0;' scrolling='no'> </iframe>"
    display(HTML(htmlCode))

Split List into Sublists with LINQ

If the list is of type system.collections.generic you can use the "CopyTo" method available to copy elements of your array to other sub arrays. You specify the start element and number of elements to copy.

You could also make 3 clones of your original list and use the "RemoveRange" on each list to shrink the list to the size you want.

Or just create a helper method to do it for you.

Function Pointers in Java

Relative to most people here I am new to java but since I haven't seen a similar suggestion I have another alternative to suggest. Im not sure if its a good practice or not, or even suggested before and I just didn't get it. I just like it since I think its self descriptive.

 /*Just to merge functions in a common name*/
 public class CustomFunction{ 
 public CustomFunction(){}
 }

 /*Actual functions*/
 public class Function1 extends CustomFunction{
 public Function1(){}
 public void execute(){...something here...}
 }

 public class Function2 extends CustomFunction{
 public Function2(){}
 public void execute(){...something here...}
 }

 .....
 /*in Main class*/
 CustomFunction functionpointer = null;

then depending on the application, assign

 functionpointer = new Function1();
 functionpointer = new Function2();

etc.

and call by

 functionpointer.execute();

INSERT INTO @TABLE EXEC @query with SQL Server 2000

DECLARE @q nvarchar(4000)
SET @q = 'DECLARE @tmp TABLE (code VARCHAR(50), mount MONEY)
INSERT INTO @tmp
  (
    code,
    mount
  )
SELECT coa_code,
       amount
FROM   T_Ledger_detail

SELECT *
FROM   @tmp'

EXEC sp_executesql @q

If you want in dynamic query

String to LocalDate

DateTimeFormatter has in-built formats that can directly be used to parse a character sequence. It is case Sensitive, Nov will work however nov and NOV wont work:

DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MMM-dd");

try {
    LocalDate datetime = LocalDate.parse(oldDate, pattern);
    System.out.println(datetime); 
} catch (DateTimeParseException e) {
    // DateTimeParseException - Text '2019-nov-12' could not be parsed at index 5
    // Exception handling message/mechanism/logging as per company standard
}

DateTimeFormatterBuilder provides custom way to create a formatter. It is Case Insensitive, Nov , nov and NOV will be treated as same.

DateTimeFormatter f = new DateTimeFormatterBuilder().parseCaseInsensitive()
        .append(DateTimeFormatter.ofPattern("yyyy-MMM-dd")).toFormatter();
try {
    LocalDate datetime = LocalDate.parse(oldDate, f);
    System.out.println(datetime); // 2019-11-12
} catch (DateTimeParseException e) {
     // Exception handling message/mechanism/logging as per company standard
}

Use multiple @font-face rules in CSS

Multiple variations of a font family can be declared by changing the font-weight and src property of @font-face rule.

/* Regular Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-Regular.ttf");
}

/* SemiBold (600) Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-SemiBold.ttf");
    font-weight: 600;
}

/* Bold Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-Bold.ttf");
    font-weight: bold;
}

Declared rules can be used by following

/* Regular */
font-family: Montserrat;


/* Semi Bold */
font-family: Montserrat;
font-weght: 600;

/* Bold */
font-family: Montserrat;
font-weight: bold;

anaconda/conda - install a specific package version

To install a specific package:

conda install <pkg>=<version>

eg:

conda install matplotlib=1.4.3

Back button and refreshing previous activity

Try This

 public void refreshActivity() {
    Intent i = new Intent(this, MainActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(i);
    finish();

}

or in Fragment

  public void refreshActivity() {
    Intent i = new Intent(getActivity(), MainActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(i);
    finish();

}

And Add this method to your onBackPressed() like

  @Override
public void onBackPressed() {      
        refreshActivity();
        super.onBackPressed();
    }
}

Thats It...

Equivalent of LIMIT for DB2

Here's the solution I came up with:

select FIELD from TABLE where FIELD > LASTVAL order by FIELD fetch first N rows only;

By initializing LASTVAL to 0 (or '' for a text field), then setting it to the last value in the most recent set of records, this will step through the table in chunks of N records.

Sort & uniq in Linux shell

I have worked on some servers where sort don't support '-u' option. there we have to use

sort xyz | uniq

HTML embedded PDF iframe

Iframe

<iframe id="fred" style="border:1px solid #666CCC" title="PDF in an i-Frame" src="PDFData.pdf" frameborder="1" scrolling="auto" height="1100" width="850" ></iframe>

Object

<object data="your_url_to_pdf" type="application/pdf">
  <embed src="your_url_to_pdf" type="application/pdf" />
</object>

CSS Margin: 0 is not setting to 0

It seems that nobody actually read your question and looked at your source code. Here's the answer you all have been waiting for:

#header_content p {
    margin-top: 0;
}

jsFiddle

jQuery Mobile Page refresh mechanism

Please take a good look here: http://jquerymobile.com/test/docs/api/methods.html

$.mobile.changePage() is to change from one page to another, and the parameter can be a url or a page object. ( only #result will also work )

$.mobile.page() isn't recommended anymore, please use .trigger( "create"), see also: JQuery Mobile .page() function causes infinite loop?

Important: Create vs. refresh: An important distinction

Note that there is an important difference between the create event and refresh method that some widgets have. The create event is suited for enhancing raw markup that contains one or more widgets. The refresh method that some widgets have should be used on existing (already enhanced) widgets that have been manipulated programmatically and need the UI be updated to match.

For example, if you had a page where you dynamically appended a new unordered list with data-role=listview attribute after page creation, triggering create on a parent element of that list would transform it into a listview styled widget. If more list items were then programmatically added, calling the listview’s refresh method would update just those new list items to the enhanced state and leave the existing list items untouched.

$.mobile.refresh() doesn't exist i guess

So what are you using for your results? A listview? Then you can update it by doing:

$('ul').listview('refresh');

Example: http://operationmobile.com/dont-forget-to-call-refresh-when-adding-items-to-your-jquery-mobile-list/

Otherwise you can do:

$('#result').live("pageinit", function(){ // or pageshow
    // your dom manipulations here
});

Can't connect to local MySQL server through socket '/tmp/mysql.sock

The relevant section of the MySQL manual is here. I'd start by going through the debugging steps listed there.

Also, remember that localhost and 127.0.0.1 are not the same thing in this context:

  • If host is set to localhost, then a socket or pipe is used.
  • If host is set to 127.0.0.1, then the client is forced to use TCP/IP.

So, for example, you can check if your database is listening for TCP connections vi netstat -nlp. It seems likely that it IS listening for TCP connections because you say that mysql -h 127.0.0.1 works just fine. To check if you can connect to your database via sockets, use mysql -h localhost.

If none of this helps, then you probably need to post more details about your MySQL config, exactly how you're instantiating the connection, etc.

"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

Personally, I ran these exact steps:

* Install Interop Assemblies: you can install from Microsoft's website https://www.microsoft.com/en-us/download/details.aspx?id=3508&tduid=(09cd06700e5e2553aa540650ec905f71)(256380)(2459594)(TnL5HPStwNw-yuTjfb1FeDiXvvZxhh.R.Q)()

* Check assemblies version: check the version of the assemblies on development and production machines. The assemblies will be in the GAC, in widows 7 this folder is %windir%\assembly.

* Create a Desktop folder: the service uses the desktop folder under systemprofile so you will need to create this folder if not there, here is the location of the folder: For 64 bit applications : C:\Windows\SysWOW64\config\systemprofile\Desktop For 32 bit applications : C:\Windows\System32\config\systemprofile\Desktop

* Add DCOM user permissions:
---start the run window and type 'dcomcnfg'.
---Expand Component Services –> Computers –> My Computer –> DCOM Config.
---Look for Microsoft Excel Application. Right click on it and select properties, then select the Security tab.
---Select the Customize radio button under 'Launch and Activation Permissions' and 'Access Permission' and click the Edit button for both to add users as follows.
---------Click the Add button and users 'IIS_IUSRS' and 'NETWORK SERVICE' and give them full privileges.
---Go to the Identity tab and select "The interactive user" option.
---Click Apply and OK.

How to preview an image before and after upload?

                    #######################
                    ###  the img page   ###
                    #######################


<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $('#f').live('change' ,function(){
            $('#fo').ajaxForm({target: '#d'}).submit();
        });
    });
</script>
<form id="fo" name="fo" action="nextimg.php" enctype="multipart/form-data" method="post">
    <input type="file" name="f" id="f" value="start upload" />
    <input type="submit" name="sub" value="upload" />
</form>
<div id="d"></div>


                    #############################
                    ###    the nextimg page   ###
                    #############################


<?php
     $name=$_FILES['f']['name'];
     $tmp=$_FILES['f']['tmp_name'];
     $new=time().$name;
     $new="upload/".$new;
     move_uploaded_file($tmp,$new);
     if($_FILES['f']['error']==0)
     {
?>
     <h1>PREVIEW</h1><br /><img src="<?php echo $new;?>" width="100" height="100" />
<?php
     }
?>

How to enable local network users to access my WAMP sites?

What finally worked for me is what I found here:

http://www.codeproject.com/Tips/395286/How-to-Access-WAMP-Server-in-LAN-or-WAN

To summarize:

  • set Listen in httpd.conf:

    Listen 192.168.1.154:8081

  • Add Allow from all to this section:

    <Directory "cgi-bin"> AllowOverride None Options None Order allow,deny Allow from all </Directory>

  • Set an inbound port rule. I think the was the crucial missing part for me:

Great! The next step is to open port (8081) of the server such that everyone can access your server. This depends on which OS you are using. Like if you are using Windows Vista, then follow the below steps.

Open Control Panel >> System and Security >> Windows Firewall then click on “Advance Setting” and then select “Inbound Rules” from the left panel and then click on “Add Rule…”. Select “PORT” as an option from the list and then in the next screen select “TCP” protocol and enter port number “8081” under “Specific local port” then click on the ”Next” button and select “Allow the Connection” and then give the general name and description to this port and click Done.

Now you are done with PORT opening as well.

Next is “Restart All Services” of WAMP and access your machine in LAN or WAN.

How to correctly implement custom iterators and const_iterators?

I'm going to show you how you can easily define iterators for your custom containers, but just in case I have created a c++11 library that allows you to easily create custom iterators with custom behavior for any type of container, contiguous or non-contiguous.

You can find it on Github

Here are the simple steps to creating and using custom iterators:

  1. Create your "custom iterator" class.
  2. Define typedefs in your "custom container" class.
    • e.g. typedef blRawIterator< Type > iterator;
    • e.g. typedef blRawIterator< const Type > const_iterator;
  3. Define "begin" and "end" functions
    • e.g. iterator begin(){return iterator(&m_data[0]);};
    • e.g. const_iterator cbegin()const{return const_iterator(&m_data[0]);};
  4. We're Done!!!

Finally, onto defining our custom iterator classes:

NOTE: When defining custom iterators, we derive from the standard iterator categories to let STL algorithms know the type of iterator we've made.

In this example, I define a random access iterator and a reverse random access iterator:

  1. //-------------------------------------------------------------------
    // Raw iterator with random access
    //-------------------------------------------------------------------
    template<typename blDataType>
    class blRawIterator
    {
    public:
    
        using iterator_category = std::random_access_iterator_tag;
        using value_type = blDataType;
        using difference_type = std::ptrdiff_t;
        using pointer = blDataType*;
        using reference = blDataType&;
    
    public:
    
        blRawIterator(blDataType* ptr = nullptr){m_ptr = ptr;}
        blRawIterator(const blRawIterator<blDataType>& rawIterator) = default;
        ~blRawIterator(){}
    
        blRawIterator<blDataType>&                  operator=(const blRawIterator<blDataType>& rawIterator) = default;
        blRawIterator<blDataType>&                  operator=(blDataType* ptr){m_ptr = ptr;return (*this);}
    
        operator                                    bool()const
        {
            if(m_ptr)
                return true;
            else
                return false;
        }
    
        bool                                        operator==(const blRawIterator<blDataType>& rawIterator)const{return (m_ptr == rawIterator.getConstPtr());}
        bool                                        operator!=(const blRawIterator<blDataType>& rawIterator)const{return (m_ptr != rawIterator.getConstPtr());}
    
        blRawIterator<blDataType>&                  operator+=(const difference_type& movement){m_ptr += movement;return (*this);}
        blRawIterator<blDataType>&                  operator-=(const difference_type& movement){m_ptr -= movement;return (*this);}
        blRawIterator<blDataType>&                  operator++(){++m_ptr;return (*this);}
        blRawIterator<blDataType>&                  operator--(){--m_ptr;return (*this);}
        blRawIterator<blDataType>                   operator++(int){auto temp(*this);++m_ptr;return temp;}
        blRawIterator<blDataType>                   operator--(int){auto temp(*this);--m_ptr;return temp;}
        blRawIterator<blDataType>                   operator+(const difference_type& movement){auto oldPtr = m_ptr;m_ptr+=movement;auto temp(*this);m_ptr = oldPtr;return temp;}
        blRawIterator<blDataType>                   operator-(const difference_type& movement){auto oldPtr = m_ptr;m_ptr-=movement;auto temp(*this);m_ptr = oldPtr;return temp;}
    
        difference_type                             operator-(const blRawIterator<blDataType>& rawIterator){return std::distance(rawIterator.getPtr(),this->getPtr());}
    
        blDataType&                                 operator*(){return *m_ptr;}
        const blDataType&                           operator*()const{return *m_ptr;}
        blDataType*                                 operator->(){return m_ptr;}
    
        blDataType*                                 getPtr()const{return m_ptr;}
        const blDataType*                           getConstPtr()const{return m_ptr;}
    
    protected:
    
        blDataType*                                 m_ptr;
    };
    //-------------------------------------------------------------------
    
  2. //-------------------------------------------------------------------
    // Raw reverse iterator with random access
    //-------------------------------------------------------------------
    template<typename blDataType>
    class blRawReverseIterator : public blRawIterator<blDataType>
    {
    public:
    
        blRawReverseIterator(blDataType* ptr = nullptr):blRawIterator<blDataType>(ptr){}
        blRawReverseIterator(const blRawIterator<blDataType>& rawIterator){this->m_ptr = rawIterator.getPtr();}
        blRawReverseIterator(const blRawReverseIterator<blDataType>& rawReverseIterator) = default;
        ~blRawReverseIterator(){}
    
        blRawReverseIterator<blDataType>&           operator=(const blRawReverseIterator<blDataType>& rawReverseIterator) = default;
        blRawReverseIterator<blDataType>&           operator=(const blRawIterator<blDataType>& rawIterator){this->m_ptr = rawIterator.getPtr();return (*this);}
        blRawReverseIterator<blDataType>&           operator=(blDataType* ptr){this->setPtr(ptr);return (*this);}
    
        blRawReverseIterator<blDataType>&           operator+=(const difference_type& movement){this->m_ptr -= movement;return (*this);}
        blRawReverseIterator<blDataType>&           operator-=(const difference_type& movement){this->m_ptr += movement;return (*this);}
        blRawReverseIterator<blDataType>&           operator++(){--this->m_ptr;return (*this);}
        blRawReverseIterator<blDataType>&           operator--(){++this->m_ptr;return (*this);}
        blRawReverseIterator<blDataType>            operator++(int){auto temp(*this);--this->m_ptr;return temp;}
        blRawReverseIterator<blDataType>            operator--(int){auto temp(*this);++this->m_ptr;return temp;}
        blRawReverseIterator<blDataType>            operator+(const int& movement){auto oldPtr = this->m_ptr;this->m_ptr-=movement;auto temp(*this);this->m_ptr = oldPtr;return temp;}
        blRawReverseIterator<blDataType>            operator-(const int& movement){auto oldPtr = this->m_ptr;this->m_ptr+=movement;auto temp(*this);this->m_ptr = oldPtr;return temp;}
    
        difference_type                             operator-(const blRawReverseIterator<blDataType>& rawReverseIterator){return std::distance(this->getPtr(),rawReverseIterator.getPtr());}
    
        blRawIterator<blDataType>                   base(){blRawIterator<blDataType> forwardIterator(this->m_ptr); ++forwardIterator; return forwardIterator;}
    };
    //-------------------------------------------------------------------
    

Now somewhere in your custom container class:

template<typename blDataType>
class blCustomContainer
{
public: // The typedefs

    typedef blRawIterator<blDataType>              iterator;
    typedef blRawIterator<const blDataType>        const_iterator;

    typedef blRawReverseIterator<blDataType>       reverse_iterator;
    typedef blRawReverseIterator<const blDataType> const_reverse_iterator;

                            .
                            .
                            .

public:  // The begin/end functions

    iterator                                       begin(){return iterator(&m_data[0]);}
    iterator                                       end(){return iterator(&m_data[m_size]);}

    const_iterator                                 cbegin(){return const_iterator(&m_data[0]);}
    const_iterator                                 cend(){return const_iterator(&m_data[m_size]);}

    reverse_iterator                               rbegin(){return reverse_iterator(&m_data[m_size - 1]);}
    reverse_iterator                               rend(){return reverse_iterator(&m_data[-1]);}

    const_reverse_iterator                         crbegin(){return const_reverse_iterator(&m_data[m_size - 1]);}
    const_reverse_iterator                         crend(){return const_reverse_iterator(&m_data[-1]);}

                            .
                            .
                            .
    // This is the pointer to the
    // beginning of the data
    // This allows the container
    // to either "view" data owned
    // by other containers or to
    // own its own data
    // You would implement a "create"
    // method for owning the data
    // and a "wrap" method for viewing
    // data owned by other containers

    blDataType*                                    m_data;
};

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Storage permission error in Marshmallow

After lots of searching This code work for me:

Check the permission already has: Check WRITE_EXTERNAL_STORAGE permission Allowed or not?

if(isReadStorageAllowed()){
            //If permission is already having then showing the toast
            //Toast.makeText(SplashActivity.this,"You already have the permission",Toast.LENGTH_LONG).show();
            //Existing the method with return
            return;
        }else{
            requestStoragePermission();
        }



private boolean isReadStorageAllowed() {
    //Getting the permission status
    int result = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);

    //If permission is granted returning true
    if (result == PackageManager.PERMISSION_GRANTED)
        return true;

    //If permission is not granted returning false
    return false;
}

//Requesting permission
private void requestStoragePermission(){

    if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)){
        //If the user has denied the permission previously your code will come to this block
        //Here you can explain why you need this permission
        //Explain here why you need this permission
    }

    //And finally ask for the permission
    ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_WRITE_STORAGE);
}

Implement Override onRequestPermissionsResult method for checking is the user allow or denie

 @Override
 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    //Checking the request code of our request
    if(requestCode == REQUEST_WRITE_STORAGE){

        //If permission is granted
        if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

            //Displaying a toast
            Toast.makeText(this,"Permission granted now you can read the storage",Toast.LENGTH_LONG).show();

        }else{
            //Displaying another toast if permission is not granted
            Toast.makeText(this,"Oops you just denied the permission",Toast.LENGTH_LONG).show();
        }
    }

pandas groupby sort within groups

You could also just do it in one go, by doing the sort first and using head to take the first 3 of each group.

In[34]: df.sort_values(['job','count'],ascending=False).groupby('job').head(3)

Out[35]: 
   count     job source
4      7   sales      E
2      6   sales      C
1      4   sales      B
5      5  market      A
8      4  market      D
6      3  market      B

Can I use CASE statement in a JOIN condition?

Here I have compared the difference in two different result sets:

SELECT main.ColumnName, compare.Value PreviousValue,  main.Value CurrentValue
FROM 
(
    SELECT 'Name' AS ColumnName, 'John' as Value UNION ALL
    SELECT 'UserName' AS ColumnName, 'jh001' as Value UNION ALL
    SELECT 'Department' AS ColumnName, 'HR' as Value UNION ALL
    SELECT 'Phone' AS ColumnName, NULL as Value UNION ALL
    SELECT 'DOB' AS ColumnName, '1993-01-01' as Value UNION ALL
    SELECT 'CreateDate' AS ColumnName, '2017-01-01' as Value UNION ALL
    SELECT 'IsActive' AS ColumnName, '1' as Value
) main
INNER JOIN
(
    SELECT 'Name' AS ColumnName, 'Rahul' as Value UNION ALL
    SELECT 'UserName' AS ColumnName, 'rh001' as Value UNION ALL
    SELECT 'Department' AS ColumnName, 'HR' as Value UNION ALL
    SELECT 'Phone' AS ColumnName, '01722112233' as Value UNION ALL
    SELECT 'DOB' AS ColumnName, '1993-01-01' as Value UNION ALL
    SELECT 'CreateDate' AS ColumnName, '2017-01-01' as Value UNION ALL
    SELECT 'IsActive' AS ColumnName, '1' as Value
) compare
ON main.ColumnName = compare.ColumnName AND
CASE 
    WHEN main.Value IS NULL AND compare.Value IS NULL THEN 0
    WHEN main.Value IS NULL AND compare.Value IS NOT NULL THEN 1
    WHEN main.Value IS NOT NULL AND compare.Value IS NULL THEN 1
    WHEN main.Value <> compare.Value THEN 1
END = 1 

Git: Merge a Remote branch locally

You can reference those remote tracking branches ~(listed with git branch -r) with the name of their remote.

You need to fetch the remote branch:

git fetch origin aRemoteBranch

If you want to merge one of those remote branches on your local branch:

git checkout master
git merge origin/aRemoteBranch

Note 1: For a large repo with a long history, you will want to add the --depth=1 option when you use git fetch.

Note 2: These commands also work with other remote repos so you can setup an origin and an upstream if you are working on a fork.

Note 3: user3265569 suggests the following alias in the comments:

From aLocalBranch, run git combine remoteBranch
Alias:

combine = !git fetch origin ${1} && git merge origin/${1}

Opposite scenario: If you want to merge one of your local branch on a remote branch (as opposed to a remote branch to a local one, as shown above), you need to create a new local branch on top of said remote branch first:

git checkout -b myBranch origin/aBranch
git merge anotherLocalBranch

The idea here, is to merge "one of your local branch" (here anotherLocalBranch) to a remote branch (origin/aBranch).
For that, you create first "myBranch" as representing that remote branch: that is the git checkout -b myBranch origin/aBranch part.
And then you can merge anotherLocalBranch to it (to myBranch).

How to find the difference in days between two dates?

This assumes that a month is 1/12 of a year:

#!/usr/bin/awk -f
function mktm(datespec) {
  split(datespec, q, "-")
  return q[1] * 365.25 + q[3] * 365.25 / 12 + q[2]
}
BEGIN {
  printf "%d\n", mktm(ARGV[2]) - mktm(ARGV[1])
}

What is a lambda expression in C++11?

Lambda expressions are typically used to encapsulate algorithms so that they can be passed to another function. However, it is possible to execute a lambda immediately upon definition:

[&](){ ...your code... }(); // immediately executed lambda expression

is functionally equivalent to

{ ...your code... } // simple code block

This makes lambda expressions a powerful tool for refactoring complex functions. You start by wrapping a code section in a lambda function as shown above. The process of explicit parameterization can then be performed gradually with intermediate testing after each step. Once you have the code-block fully parameterized (as demonstrated by the removal of the &), you can move the code to an external location and make it a normal function.

Similarly, you can use lambda expressions to initialize variables based on the result of an algorithm...

int a = []( int b ){ int r=1; while (b>0) r*=b--; return r; }(5); // 5!

As a way of partitioning your program logic, you might even find it useful to pass a lambda expression as an argument to another lambda expression...

[&]( std::function<void()> algorithm ) // wrapper section
   {
   ...your wrapper code...
   algorithm();
   ...your wrapper code...
   }
([&]() // algorithm section
   {
   ...your algorithm code...
   });

Lambda expressions also let you create named nested functions, which can be a convenient way of avoiding duplicate logic. Using named lambdas also tends to be a little easier on the eyes (compared to anonymous inline lambdas) when passing a non-trivial function as a parameter to another function. Note: don't forget the semicolon after the closing curly brace.

auto algorithm = [&]( double x, double m, double b ) -> double
   {
   return m*x+b;
   };

int a=algorithm(1,2,3), b=algorithm(4,5,6);

If subsequent profiling reveals significant initialization overhead for the function object, you might choose to rewrite this as a normal function.

TypeError: only length-1 arrays can be converted to Python scalars while plot showing

The error "only length-1 arrays can be converted to Python scalars" is raised when the function expects a single value but you pass an array instead.

If you look at the call signature of np.int, you'll see that it accepts a single value, not an array. In general, if you want to apply a function that accepts a single element to every element in an array, you can use np.vectorize:

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return np.int(x)
f2 = np.vectorize(f)
x = np.arange(1, 15.1, 0.1)
plt.plot(x, f2(x))
plt.show()

You can skip the definition of f(x) and just pass np.int to the vectorize function: f2 = np.vectorize(np.int).

Note that np.vectorize is just a convenience function and basically a for loop. That will be inefficient over large arrays. Whenever you have the possibility, use truly vectorized functions or methods (like astype(int) as @FFT suggests).

How to capture the android device screen content?

According to this link, it is possible to use ddms in the tools directory of the android sdk to take screen captures.

To do this within an application (and not during development), there are also applications to do so. But as @zed_0xff points out it certainly requires root.

How to get controls in WPF to fill available space?

Use the HorizontalAlignment and VerticalAlignment layout properties. They control how an element uses the space it has inside its parent when more room is available than it required by the element.

The width of a StackPanel, for example, will be as wide as the widest element it contains. So, all narrower elements have a bit of excess space. The alignment properties control what the child element does with the extra space.

The default value for both properties is Stretch, so the child element is stretched to fill all available space. Additional options include Left, Center and Right for HorizontalAlignment and Top, Center and Bottom for VerticalAlignment.

Get mouse wheel events in jQuery?

I was stuck in this issue today and found this code is working fine for me

$('#content').on('mousewheel', function(event) {
    //console.log(event.deltaX, event.deltaY, event.deltaFactor);
    if(event.deltaY > 0) {
      console.log('scroll up');
    } else {
      console.log('scroll down');
    }
});

Do subclasses inherit private fields?

It depends on your definition of "inherit". Does the subclass still have the fields in memory? Definitely. Can it access them directly? No. It's just subtleties of the definition; the point is to understand what's really happening.

How do I set the version information for an existing .exe, .dll?

verpatch is good, but doesn't handle unicode characters...
try ResourceLib

Using msbuild to execute a File System Publish Profile

Still had trouble after trying all of the answers above (I use Visual Studio 2013). Nothing was copied to the publish folder.

The catch was that if I run MSBuild with an individual project instead of a solution, I have to put an additional parameter that specifies Visual Studio version:

/p:VisualStudioVersion=12.0

12.0 is for VS2013, replace with the version you use. Once I added this parameter, it just worked.

The complete command line looks like this:

MSBuild C:\PathToMyProject\MyProject.csproj /p:DeployOnBuild=true /p:PublishProfile=MyPublishProfile /p:VisualStudioVersion=12.0

I've found it here:

http://www.asp.net/mvc/overview/deployment/visual-studio-web-deployment/command-line-deployment

They state:

If you specify an individual project instead of a solution, you have to add a parameter that specifies the Visual Studio version.

Can I run HTML files directly from GitHub, instead of just viewing their source?

This solution only for chrome browser. I am not sure about other browser.

  1. Add "Modify Content-Type Options" extension in chrome browser.
  2. Open "chrome-extension://jnfofbopfpaoeojgieggflbpcblhfhka/options.html" url in browser.
  3. Add the rule for raw file url. For example:
    • URL Filter: https:///raw/master//fileName.html
    • Original Type: text/plain
    • Replacement Type: text/html
  4. Open the file browser which you added url in rule (in step 3).

How can I exclude multiple folders using Get-ChildItem -exclude?

My KISS approach to skip some folders is chaining Get-ChildItem calls. This excludes root level folders but not deeper level folders if that is what you want.

Get-ChildItem -Exclude folder1,folder2 | Get-ChildItem -Recurse | ...
  • Start excluding folders you don't want
  • Then do the recursive search with non desired folders excluded.

What I like from this approach is that it is simple and easy to remember. If you don't want to mix folders and files in the first search a filter would be needed.

Better way to call javascript function in a tag

Modern browsers support a Content Security Policy or CSP. This is the highest level of web security and strongly recommended if you can apply it because it completely blocks all XSS attacks.

Both of your suggestions break with CSP enabled because they allow inline Javascript (which could be injected by a hacker) to execute in your page.

The best practice is to subscribe to the event in Javascript, as in Konrad Rudolph's answer.

Where is shared_ptr?

for VS2008 with feature pack update, shared_ptr can be found under namespace std::tr1.

std::tr1::shared_ptr<int> MyIntSmartPtr = new int;

of

if you had boost installation path (for example @ C:\Program Files\Boost\boost_1_40_0) added to your IDE settings:

#include <boost/shared_ptr.hpp>

How can I count occurrences with groupBy?

Here is the simple solution by StreamEx:

StreamEx.of(list).groupingBy(Function.identity(), MoreCollectors.countingInt());

This has the advantage of reducing the Java stream boilerplate code: collect(Collectors.

How do I install PHP cURL on Linux Debian?

Whatever approach you take, make sure in the end that you have an updated version of curl and libcurl. You can do curl --version and see the versions.

Here's what I did to get the latest curl version installed in Ubuntu:

  1. sudo add-apt-repository "deb http://mirrors.kernel.org/ubuntu wily main"
  2. sudo apt-get update
  3. sudo apt-get install curl

How to customize the configuration file of the official PostgreSQL Docker image?

With Docker Compose

When working with Docker Compose, you can use command: postgres -c option=value in your docker-compose.yml to configure Postgres.

For example, this makes Postgres log to a file:

command: postgres -c logging_collector=on -c log_destination=stderr -c log_directory=/logs

Adapting Vojtech Vitek's answer, you can use

command: postgres -c config_file=/etc/postgresql.conf

to change the config file Postgres will use. You'd mount your custom config file with a volume:

volumes:
   - ./customPostgresql.conf:/etc/postgresql.conf

Here's the docker-compose.yml of my application, showing how to configure Postgres:

# Start the app using docker-compose pull && docker-compose up to make sure you have the latest image
version: '2.1'
services:
  myApp:
    image: registry.gitlab.com/bullbytes/myApp:latest
    networks:
      - myApp-network
  db:
     image: postgres:9.6.1
     # Make Postgres log to a file.
     # More on logging with Postgres: https://www.postgresql.org/docs/current/static/runtime-config-logging.html
     command: postgres -c logging_collector=on -c log_destination=stderr -c log_directory=/logs
     environment:
       # Provide the password via an environment variable. If the variable is unset or empty, use a default password
       - POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-4WXUms893U6j4GE&Hvk3S*hqcqebFgo!vZi}
     # If on a non-Linux OS, make sure you share the drive used here. Go to Docker's settings -> Shared Drives
     volumes:
       # Persist the data between container invocations
       - postgresVolume:/var/lib/postgresql/data
       - ./logs:/logs
     networks:
       myApp-network:
         # Our application can communicate with the database using this hostname
         aliases:
           - postgresForMyApp
networks:
  myApp-network:
    driver: bridge
# Creates a named volume to persist our data. When on a non-Linux OS, the volume's data will be in the Docker VM
# (e.g., MobyLinuxVM) in /var/lib/docker/volumes/
volumes:
  postgresVolume:

Permission to write to the log directory

Note that when on Linux, the log directory on the host must have the right permissions. Otherwise you'll get the slightly misleading error

FATAL: could not open log file "/logs/postgresql-2017-02-04_115222.log": Permission denied

I say misleading, since the error message suggests that the directory in the container has the wrong permission, when in reality the directory on the host doesn't permit writing.

To fix this, I set the correct permissions on the host using

chgroup ./logs docker && chmod 770 ./logs

List<object>.RemoveAll - How to create an appropriate Predicate

A predicate in T is a delegate that takes in a T and returns a bool. List<T>.RemoveAll will remove all elements in a list where calling the predicate returns true. The easiest way to supply a simple predicate is usually a lambda expression, but you can also use anonymous methods or actual methods.

{
    List<Vehicle> vehicles;
    // Using a lambda
    vehicles.RemoveAll(vehicle => vehicle.EnquiryID == 123);
    // Using an equivalent anonymous method
    vehicles.RemoveAll(delegate(Vehicle vehicle)
    {
        return vehicle.EnquiryID == 123;
    });
    // Using an equivalent actual method
    vehicles.RemoveAll(VehiclePredicate);
}

private static bool VehiclePredicate(Vehicle vehicle)
{
    return vehicle.EnquiryID == 123;
}

How do I split a string into an array of characters?

You can use the regular expression /(?!$)/:

"overpopulation".split(/(?!$)/)

The negative look-ahead assertion (?!$) will match right in front of every character.

Argparse: Required arguments listed under "optional arguments"?

One more time, building off of @RalphyZ

This one doesn't break the exposed API.

from argparse import ArgumentParser, SUPPRESS
# Disable default help
parser = ArgumentParser(add_help=False)
required = parser.add_argument_group('required arguments')
optional = parser.add_argument_group('optional arguments')

# Add back help 
optional.add_argument(
    '-h',
    '--help',
    action='help',
    default=SUPPRESS,
    help='show this help message and exit'
)
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')

Which will show the same as above and should survive future versions:

usage: main.py [-h] [--required_arg REQUIRED_ARG]
           [--optional_arg OPTIONAL_ARG]

required arguments:
  --required_arg REQUIRED_ARG

optional arguments:
  -h, --help                    show this help message and exit
  --optional_arg OPTIONAL_ARG

Pandas index column title or name

df.columns.values also give us the column names

Placeholder in IE9

HTML5 Placeholder jQuery Plugin
- by Mathias Bynens (a collaborator on HTML5 Boilerplate and jsPerf)

https://github.com/mathiasbynens/jquery-placeholder

Demo & Examples

http://mathiasbynens.be/demo/placeholder

p.s
I have used this plugin many times and it works a treat. Also it doesn't submit the placeholder text as a value when you submit your form (... a real pain I found with other plugins).

Finding the average of a list

suppose that

x = [
    [-5.01,-5.43,1.08,0.86,-2.67,4.94,-2.51,-2.25,5.56,1.03],
    [-8.12,-3.48,-5.52,-3.78,0.63,3.29,2.09,-2.13,2.86,-3.33],
    [-3.68,-3.54,1.66,-4.11,7.39,2.08,-2.59,-6.94,-2.26,4.33]
]

you can notice that x has dimension 3*10 if you need to get the mean to each row you can type this

theMean = np.mean(x1,axis=1)

don't forget to import numpy as np

Cannot connect to the Docker daemon on macOS

I had the same problem. Docker running but couldn't access it through CLI.

For me the problem was solved by executing "Docker Quickstart Terminal.app". This is located in the "/Applications/Docker/" folder. As long as I work in this instance of the Terminal app Docker works perfectly. If a second window is needed I have to run the "Quickstart" app once more.

I have a Docker for Mac installation. Therefore I am not sure if my solution is valid for a Homebrew installation.

The "Docker Quickstart Terminal" app seems to be essentially some applescripts to launch the terminal app and a bash start script that initialise all the necessary environment variables.

Hope this helps someone else !

mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

Simply put, you need to rewrite all of your database connections and queries.

You are using mysql_* functions which are now deprecated and will be removed from PHP in the future. So you need to start using MySQLi or PDO instead, just as the error notice warned you.

A basic example of using PDO (without error handling):

<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$result = $db->exec("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
$insertId = $db->lastInsertId();
?>

A basic example of using MySQLi (without error handling):

$db = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
$result = $db->query("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");

Here's a handy little PDO tutorial to get you started. There are plenty of others, and ones about the PDO alternative, MySQLi.

Drop multiple tables in one shot in MySQL

SET foreign_key_checks = 0;
DROP TABLE IF EXISTS a,b,c;
SET foreign_key_checks = 1;

Then you do not have to worry about dropping them in the correct order, nor whether they actually exist.

N.B. this is for MySQL only (as in the question). Other databases likely have different methods for doing this.

What in layman's terms is a Recursive Function using PHP

It is very simple, when a function calls itself for accomplishing a task for undefined and finite number of time. An example from my own code, function for populating a with multilevel category tree

function category_tree($parent=0,$sep='')
{
    $q="select id,name from categorye where parent_id=".$parent;
    $rs=mysql_query($q);
    while($rd=mysql_fetch_object($rs))
    {
        echo('id.'">'.$sep.$rd->name.'');
        category_tree($rd->id,$sep.'--');
    }
}

How do you get the length of a list in the JSF expression language?

You can get the length using the following EL:

#{Bean.list.size()}

Div 100% height works on Firefox but not in IE

You might have to put one or both of:

html { height:100%; }

or

body { height:100%; }

EDIT: Whoops, didn't notice they were floated. You just need to float the container.

Is it possible to write data to file using only JavaScript?

If you are talking about browser javascript, you can not write data directly to local file for security reason. HTML 5 new API can only allow you to read files.

But if you want to write data, and enable user to download as a file to local. the following code works:

    function download(strData, strFileName, strMimeType) {
    var D = document,
        A = arguments,
        a = D.createElement("a"),
        d = A[0],
        n = A[1],
        t = A[2] || "text/plain";

    //build download link:
    a.href = "data:" + strMimeType + "charset=utf-8," + escape(strData);


    if (window.MSBlobBuilder) { // IE10
        var bb = new MSBlobBuilder();
        bb.append(strData);
        return navigator.msSaveBlob(bb, strFileName);
    } /* end if(window.MSBlobBuilder) */



    if ('download' in a) { //FF20, CH19
        a.setAttribute("download", n);
        a.innerHTML = "downloading...";
        D.body.appendChild(a);
        setTimeout(function() {
            var e = D.createEvent("MouseEvents");
            e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            a.dispatchEvent(e);
            D.body.removeChild(a);
        }, 66);
        return true;
    }; /* end if('download' in a) */



    //do iframe dataURL download: (older W3)
    var f = D.createElement("iframe");
    D.body.appendChild(f);
    f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + "," + (window.btoa ? window.btoa : escape)(strData);
    setTimeout(function() {
        D.body.removeChild(f);
    }, 333);
    return true;
}

to use it:

download('the content of the file', 'filename.txt', 'text/plain');

How do I resolve "Please make sure that the file is accessible and that it is a valid assembly or COM component"?

In my case I also have unmanaged dll's (C++) in workspace and if you specify:

<files>
    <file src="bin\*.dll" target="lib" />
</files>

nuget would try to load every dll as an assembly, even the C++ libraries! To avoid this behaviour explicitly define your C# assemblies with references tag:

<references>
    <reference file="Managed1.dll" />
    <reference file="Managed2.dll" />
</references>

Remark: parent of references is metadata -> according to documentation https://docs.microsoft.com/en-us/nuget/reference/nuspec#general-form-and-schema

Documentation: https://docs.microsoft.com/en-us/nuget/reference/nuspec

Stop form refreshing page on submit

Just found a very simple yet working solution, by removing <form></form> from the section I wanted to prevent from posting and refreshing.

<select id="youId" name="yourName">
<select> 
<option value="1</option>
<option value="2</option>
<option value="3</option>
</select>
<input id="formStockVal1" type="number"><br><br>
<form> 
<button type="reset" id="stockCancel">Cancel</button>
<button type="reset" id="stockConfirm">Add</button>
</form>

Here only Buttons submit as they should.

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

Make sure that the database is created. I got the same error when I applied the migration to the wrong project in the solution. When I applied the migration to the right project, it created the database and that solved the error.

CSS strikethrough different color from text?

Here you go:

_x000D_
_x000D_
<style>body {color: #000;}</style>_x000D_
<del>&nbsp;&nbsp;<span style="color:#999">facebook</span>&nbsp;&nbsp;</del>
_x000D_
_x000D_
_x000D_

Python [Errno 98] Address already in use

If you use a TCPServer, UDPServer or their subclasses in the SocketServer module, you can set this class variable (before instanciating a server):

SocketServer.TCPServer.allow_reuse_address = True

(via SocketServer.ThreadingTCPServer - Cannot bind to address after program restart )

This causes the init (constructor) to:

 if self.allow_reuse_address:
     self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

docker cannot start on windows

Error Code:

error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.29/version: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect . This error may also indicate that the docker daemon is not running.

Solutions:

1) For Windows 7 Command Window(cmd.exe), open cmd.exe with run as administrator and execute following command:

docker-machine env --shell cmd default

You will receive following output:

SET DOCKER_TLS_VERIFY=1
SET DOCKER_HOST=tcp://192.168.99.100:2376
SET DOCKER_CERT_PATH=C:\Users\USER_NAME\.docker\machine\machines\default
SET DOCKER_MACHINE_NAME=default
SET COMPOSE_CONVERT_WINDOWS_PATHS=true
REM Run this command to configure your shell:
REM @FOR /f "tokens=*" %i IN ('docker-machine env --shell cmd default') DO @%i

Copy the command below and execute on cmd:

@FOR /f "tokens=*" %i IN ('docker-machine env --shell cmd default') DO @%i

And then execute following command to control:

docker version

2) For Windows 7 Powershell, open powershell.exe with run as administrator and execute following command:

docker-machine env --shell=powershell | Invoke-Expression

And then execute following command to control:

docker version

3) If you reopen cmd or powershell, you should repeat the related steps again.

Disable Auto Zoom in Input "Text" tag - Safari on iPhone

In summary the answer is: set the font size of the form elements to at least 16px

Using Regular Expressions to Extract a Value in Java

if you are reading from file then this can help you

              try{
             InputStream inputStream = (InputStream) mnpMainBean.getUploadedBulk().getInputStream();
             BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
             String line;
             //Ref:03
             while ((line = br.readLine()) != null) {
                if (line.matches("[A-Z],\\d,(\\d*,){2}(\\s*\\d*\\|\\d*:)+")) {
                     String[] splitRecord = line.split(",");
                     //do something
                 }
                 else{
                     br.close();
                     //error
                     return;
                 }
             }
                br.close();

             }
         }
         catch (IOException  ioExpception){
             logger.logDebug("Exception " + ioExpception.getStackTrace());
         }

How to safely call an async method in C# without await

If you really wants to do this. Just to address "Call an async method in C# without await", you can execute the async method inside a Task.Run. This approach will wait until MyAsyncMethod finish.

public string GetStringData()
{
    Task.Run(()=> MyAsyncMethod()).Result;
    return "hello world";
}

await asynchronously unwraps the Result of your task, whereas just using Result would block until the task had completed.

SQL Server: the maximum number of rows in table

We have tables in SQL Server 2005 and 2008 with over 1 Billion rows in it (30 million added daily). I can't imagine going down the rats nest of splitting that out into a new table each day.

Much cheaper to add the appropriate disk space (which you need anyway) and RAM.

Getting IP address of client

As @martin and this answer explained, it is complicated. There is no bullet-proof way of getting the client's ip address.

The best that you can do is to try to parse "X-Forwarded-For" and rely on request.getRemoteAddr();

public static String getClientIpAddress(HttpServletRequest request) {
    String xForwardedForHeader = request.getHeader("X-Forwarded-For");
    if (xForwardedForHeader == null) {
        return request.getRemoteAddr();
    } else {
        // As of https://en.wikipedia.org/wiki/X-Forwarded-For
        // The general format of the field is: X-Forwarded-For: client, proxy1, proxy2 ...
        // we only want the client
        return new StringTokenizer(xForwardedForHeader, ",").nextToken().trim();
    }
}

How to parse JSON boolean value?

Try this:

{
    "ACCOUNT_EXIST": true,
    "MultipleContacts": false
}

boolean success ((Boolean) jsonObject.get("ACCOUNT_EXIST")).booleanValue()

Difference between Running and Starting a Docker container

run command creates a container from the image and then starts the root process on this container. Running it with run --rm flag would save you the trouble of removing the useless dead container afterward and would allow you to ignore the existence of docker start and docker remove altogether.

enter image description here

run command does a few different things:

docker run --name dname image_name bash -c "whoami"
  1. Creates a Container from the image. At this point container would have an id, might have a name if one is given, will show up in docker ps
  2. Starts/executes the root process of the container. In the code above that would execute bash -c "whoami". If one runs docker run --name dname image_name without a command to execute container would go into stopped state immediately.
  3. Once the root process is finished, the container is stopped. At this point, it is pretty much useless. One can not execute anything anymore or resurrect the container. There are basically 2 ways out of stopped state: remove the container or create a checkpoint (i.e. an image) out of stopped container to run something else. One has to run docker remove before launching container under the same name.

How to remove container once it is stopped automatically? Add an --rm flag to run command:

docker run --rm --name dname image_name bash -c "whoami"

How to execute multiple commands in a single container? By preventing that root process from dying. This can be done by running some useless command at start with --detached flag and then using "execute" to run actual commands:

docker run --rm -d --name dname image_name tail -f /dev/null
docker exec dname bash -c "whoami"
docker exec dname bash -c "echo 'Nnice'"

Why do we need docker stop then? To stop this lingering container that we launched in the previous snippet with the endless command tail -f /dev/null.

SQL NVARCHAR and VARCHAR Limits

Okay, so if later on down the line the issue is that you have a query that's greater than the allowable size (which may happen if it keeps growing) you're going to have to break it into chunks and execute the string values. So, let's say you have a stored procedure like the following:

CREATE PROCEDURE ExecuteMyHugeQuery
    @SQL VARCHAR(MAX) -- 2GB size limit as stated by Martin Smith
AS
BEGIN
    -- Now, if the length is greater than some arbitrary value
    -- Let's say 2000 for this example
    -- Let's chunk it
    -- Let's also assume we won't allow anything larger than 8000 total
    DECLARE @len INT
    SELECT @len = LEN(@SQL)

    IF (@len > 8000)
    BEGIN
        RAISERROR ('The query cannot be larger than 8000 characters total.',
                   16,
                   1);
    END

    -- Let's declare our possible chunks
    DECLARE @Chunk1 VARCHAR(2000),
            @Chunk2 VARCHAR(2000),
            @Chunk3 VARCHAR(2000),
            @Chunk4 VARCHAR(2000)

    SELECT @Chunk1 = '',
           @Chunk2 = '',
           @Chunk3 = '',
           @Chunk4 = ''

    IF (@len > 2000)
    BEGIN
        -- Let's set the right chunks
        -- We already know we need two chunks so let's set the first
        SELECT @Chunk1 = SUBSTRING(@SQL, 1, 2000)

        -- Let's see if we need three chunks
        IF (@len > 4000)
        BEGIN
            SELECT @Chunk2 = SUBSTRING(@SQL, 2001, 2000)

            -- Let's see if we need four chunks
            IF (@len > 6000)
            BEGIN
                SELECT @Chunk3 = SUBSTRING(@SQL, 4001, 2000)
                SELECT @Chunk4 = SUBSTRING(@SQL, 6001, (@len - 6001))
            END
              ELSE
            BEGIN
                SELECT @Chunk3 = SUBSTRING(@SQL, 4001, (@len - 4001))
            END
        END
          ELSE
        BEGIN
            SELECT @Chunk2 = SUBSTRING(@SQL, 2001, (@len - 2001))
        END
    END

    -- Alright, now that we've broken it down, let's execute it
    EXEC (@Chunk1 + @Chunk2 + @Chunk3 + @Chunk4)
END

How to use a jQuery plugin inside Vue

Suppose you have Vue project created with vue-cli (e.g. vue init webpack my-project). Go to project dir and run

npm install jquery --save

Open file build/webpack.base.conf.js and add plugins:

module.exports = {
  plugins: [
    new webpack.ProvidePlugin({
      $: 'jquery',
      jquery: 'jquery',
      'window.jQuery': 'jquery',
      jQuery: 'jquery'
    })
  ]
  ...
}

Also at top of file add:

const webpack = require('webpack')

If you are using ESLint, open .eslintrc.js and add next globals: {

module.exports = {
  globals: {
    "$": true,
    "jQuery": true
  },
  ...

Now you are ready to go. Use $ anywhere in your js.

NOTE You don't need to include expose loader or any other stuff to use this.

Originally from https://maketips.net/tip/223/how-to-include-jquery-into-vuejs

What is the easiest way to get current GMT time in Unix timestamp format?

python2 and python3

it is good to use time module

import time
int(time.time())

1573708436

you can also use datetime module, but when you use strftime('%s'), but strftime convert time to your local time!

python2

from datetime import datetime
datetime.utcnow().strftime('%s')

python3

from datetime import datetime
datetime.utcnow().timestamp()

Dynamically set value of a file input

It is not possible to dynamically change the value of a file field, otherwise you could set it to "c:\yourfile" and steal files very easily.

However there are many solutions to a multi-upload system. I'm guessing that you're wanting to have a multi-select open dialog.

Perhaps have a look at http://www.plupload.com/ - it's a very flexible solution to multiple file uploads, and supports drop zones e.t.c.

Printing variables in Python 3.4

Try the format syntax:

print ("{0}. {1} appears {2} times.".format(1, 'b', 3.1415))

Outputs:

1. b appears 3.1415 times.

The print function is called just like any other function, with parenthesis around all its arguments.

How to convert wstring into string?

// Embarcadero C++ Builder 

// convertion string to wstring
string str1 = "hello";
String str2 = str1;         // typedef UnicodeString String;   -> str2 contains now u"hello";

// convertion wstring to string
String str2 = u"hello";
string str1 = UTF8string(str2).c_str();   // -> str1 contains now "hello"

Python Git Module experiences?

PTBNL's Answer is quite perfect for me. I make a little more for Windows user.

import time
import subprocess
def gitAdd(fileName, repoDir):
    cmd = 'git add ' + fileName
    pipe = subprocess.Popen(cmd, shell=True, cwd=repoDir,stdout = subprocess.PIPE,stderr = subprocess.PIPE )
    (out, error) = pipe.communicate()
    print out,error
    pipe.wait()
    return 

def gitCommit(commitMessage, repoDir):
    cmd = 'git commit -am "%s"'%commitMessage
    pipe = subprocess.Popen(cmd, shell=True, cwd=repoDir,stdout = subprocess.PIPE,stderr = subprocess.PIPE )
    (out, error) = pipe.communicate()
    print out,error
    pipe.wait()
    return 
def gitPush(repoDir):
    cmd = 'git push '
    pipe = subprocess.Popen(cmd, shell=True, cwd=repoDir,stdout = subprocess.PIPE,stderr = subprocess.PIPE )
    (out, error) = pipe.communicate()
    pipe.wait()
    return 

temp=time.localtime(time.time())
uploaddate= str(temp[0])+'_'+str(temp[1])+'_'+str(temp[2])+'_'+str(temp[3])+'_'+str(temp[4])

repoDir='d:\\c_Billy\\vfat\\Programming\\Projector\\billyccm' # your git repository , windows your need to use double backslash for right directory.
gitAdd('.',repoDir )
gitCommit(uploaddate, repoDir)
gitPush(repoDir)

Switch/toggle div (jQuery)

This is how I toggle two divs at the same time:

$('#login-form, #recover-password').toggle();

It works!

How to get a key in a JavaScript object by its value?

Underscore js solution

let samplLst = [{id:1,title:Lorem},{id:2,title:Ipsum}]
let sampleKey = _.findLastIndex(samplLst,{_id:2});
//result would be 1
console.log(samplLst[sampleKey])
//output - {id:2,title:Ipsum}

Android Spinner: Get the selected item change event

Some of the previous answers are not correct. They work for other widgets and views, but the documentation for the Spinner widget clearly states:

A spinner does not support item click events. Calling this method will raise an exception.

Better use OnItemSelectedListener() instead:

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        // your code here
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {
        // your code here
    }

});

This works for me.

Note that onItemSelected method is also invoked when the view is being build, so you can consider putting it inside onCreate() method call.

How to load images dynamically (or lazily) when users scrolls them into view

I came up with my own basic method which seems to work fine (so far). There's probably a dozen things some of the popular scripts address that I haven't thought of.

Note - This solution is fast and easy to implement but of course not great for performance. Definitely look into the new Intersection Observer as mentioned by Apoorv and explained by developers.google if performance is an issue.

The JQuery

$(window).scroll(function() {
    $.each($('img'), function() {
        if ( $(this).attr('data-src') && $(this).offset().top < ($(window).scrollTop() + $(window).height() + 100) ) {
            var source = $(this).data('src');
            $(this).attr('src', source);
            $(this).removeAttr('data-src');
        }
    })
})

Sample html code

<div>
    <img src="" data-src="pathtoyour/image1.jpg">
    <img src="" data-src="pathtoyour/image2.jpg">
    <img src="" data-src="pathtoyour/image3.jpg">
</div>

Explained

When the page is scrolled each image on the page is checked..

$(this).attr('data-src') - if the image has the attribute data-src

and how far those images are from the bottom of the window..

$(this).offset().top < ($(window).scrollTop() + $(window).height() + 100)

adjust the + 100 to whatever you like (- 100 for example)

var source = $(this).data('src'); - gets the value of data-src= aka the image url

$(this).attr('src', source); - puts that value into the src=

$(this).removeAttr('data-src'); - removes the data-src attribute (so your browser doesn't waste resources messing with the images that have already loaded)

Adding To Existing Code

To convert your html, in an editor just search and replace src=" with src="" data-src="

What is a mutex?

Mutexes are useful in situations where you need to enforce exclusive access to a resource accross multiple processes, where a regular lock won't help since it only works accross threads.

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

I had the same problem, and my solution was to eliminate the line

android:screenOrientation="portrait"

and then add this in the activity:

if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

Get selected option from select element

Try this:

$('#ddlCodes').change(function() {
  var option = this.options[this.selectedIndex];
  $('#txtEntry2').text($(option).text());
});

What is a database transaction?

In addition to the above responses, it should be noted that there is, at least in theory, no restriction whatsoever as to what kind of resources are involved in a transaction.

Most of the time, it is just a database, or multiple distinct databases, but it is also conceivable that a printer takes part in a transaction, and can cause that transaction to fail, say in the event of a paper jam.

How do I enable index downloads in Eclipse for Maven dependency search?

  1. In Eclipse, click on Windows > Preferences, and then choose Maven in the left side.
  2. Check the box "Download repository index updates on startup".
    • Optionally, check the boxes Download Artifact Sources and Download Artifact JavaDoc.
  3. Click OK. The warning won't appear anymore.
  4. Restart Eclipse.

http://i.imgur.com/IJ2T3vc.png

How do I hide an element on a click event anywhere outside of the element?

Here is a working CSS/small JS solution based on the answer of Sandeep Pal:

$(document).click(function (e)
{
  if (!$("#noticeMenu").is(e.target) && $("#noticeMenu").has(e.target).length == 0)
  {
   $("#menu-toggle3").prop('checked', false);
  }
});

Try it out by clicking the checkbox and then outside of the menu:

https://jsfiddle.net/qo90txr8/

Selecting a Linux I/O Scheduler

As documented in /usr/src/linux/Documentation/block/switching-sched.txt, the I/O scheduler on any particular block device can be changed at runtime. There may be some latency as the previous scheduler's requests are all flushed before bringing the new scheduler into use, but it can be changed without problems even while the device is under heavy use.

# cat /sys/block/hda/queue/scheduler
noop deadline [cfq]
# echo anticipatory > /sys/block/hda/queue/scheduler
# cat /sys/block/hda/queue/scheduler
noop [deadline] cfq

Ideally, there would be a single scheduler to satisfy all needs. It doesn't seem to exist yet. The kernel often doesn't have enough knowledge to choose the best scheduler for your workload:

  • noop is often the best choice for memory-backed block devices (e.g. ramdisks) and other non-rotational media (flash) where trying to reschedule I/O is a waste of resources
  • deadline is a lightweight scheduler which tries to put a hard limit on latency
  • cfq tries to maintain system-wide fairness of I/O bandwidth

The default was anticipatory for a long time, and it received a lot of tuning, but was removed in 2.6.33 (early 2010). cfq became the default some while ago, as its performance is reasonable and fairness is a good goal for multi-user systems (and even single-user desktops). For some scenarios -- databases are often used as examples, as they tend to already have their own peculiar scheduling and access patterns, and are often the most important service (so who cares about fairness?) -- anticipatory has a long history of being tunable for best performance on these workloads, and deadline very quickly passes all requests through to the underlying device.

Get folder name from full file path

I figured there's no way except going into the file system to find out if text.txt is a directory or just a file. If you wanted something simple, maybe you can just use:

s.Substring(s.LastIndexOf(@"\"));

Fluid or fixed grid system, in responsive design, based on Twitter Bootstrap

Fluid layout in Bootstrap 3.

Unlike Boostrap 2, Bootstrap 3 doesn't have a .container-fluid mixin to make a fluid container. The .container is a fixed width responsive grid layout. In a large screen, there are excessive white spaces in both sides of one's Web page content.

container-fluid is added back in Bootstrap 3.1

A fluid grid layout uses all screen width and works better in large screen. It turns out that it is easy to create a fluid grid layout using Bootstrap 3 mixins. The following line makes a fluid responsive grid layout:

.container-fixed;

The .container-fixed mixin sets the content to the center of the screen and add paddings. It doesn't specifies a fixed page width.

Another approach is to use Eric Flowers' CSS style

.my-fluid-container {
    padding-left: 15px;
    padding-right: 15px;
    margin-left: auto;
    margin-right: auto;
}

Spring Test & Security: How to mock authentication?

Seaching for answer I couldn't find any to be easy and flexible at the same time, then I found the Spring Security Reference and I realized there are near to perfect solutions. AOP solutions often are the greatest ones for testing, and Spring provides it with @WithMockUser, @WithUserDetails and @WithSecurityContext, in this artifact:

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <version>4.2.2.RELEASE</version>
    <scope>test</scope>
</dependency>

In most cases, @WithUserDetails gathers the flexibility and power I need.

How @WithUserDetails works?

Basically you just need to create a custom UserDetailsService with all the possible users profiles you want to test. E.g

@TestConfiguration
public class SpringSecurityWebAuxTestConfig {

    @Bean
    @Primary
    public UserDetailsService userDetailsService() {
        User basicUser = new UserImpl("Basic User", "[email protected]", "password");
        UserActive basicActiveUser = new UserActive(basicUser, Arrays.asList(
                new SimpleGrantedAuthority("ROLE_USER"),
                new SimpleGrantedAuthority("PERM_FOO_READ")
        ));

        User managerUser = new UserImpl("Manager User", "[email protected]", "password");
        UserActive managerActiveUser = new UserActive(managerUser, Arrays.asList(
                new SimpleGrantedAuthority("ROLE_MANAGER"),
                new SimpleGrantedAuthority("PERM_FOO_READ"),
                new SimpleGrantedAuthority("PERM_FOO_WRITE"),
                new SimpleGrantedAuthority("PERM_FOO_MANAGE")
        ));

        return new InMemoryUserDetailsManager(Arrays.asList(
                basicActiveUser, managerActiveUser
        ));
    }
}

Now we have our users ready, so imagine we want to test the access control to this controller function:

@RestController
@RequestMapping("/foo")
public class FooController {

    @Secured("ROLE_MANAGER")
    @GetMapping("/salute")
    public String saluteYourManager(@AuthenticationPrincipal User activeUser)
    {
        return String.format("Hi %s. Foo salutes you!", activeUser.getUsername());
    }
}

Here we have a get mapped function to the route /foo/salute and we are testing a role based security with the @Secured annotation, although you can test @PreAuthorize and @PostAuthorize as well. Let's create two tests, one to check if a valid user can see this salute response and the other to check if it's actually forbidden.

@RunWith(SpringRunner.class)
@SpringBootTest(
        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
        classes = SpringSecurityWebAuxTestConfig.class
)
@AutoConfigureMockMvc
public class WebApplicationSecurityTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    @WithUserDetails("[email protected]")
    public void givenManagerUser_whenGetFooSalute_thenOk() throws Exception
    {
        mockMvc.perform(MockMvcRequestBuilders.get("/foo/salute")
                .accept(MediaType.ALL))
                .andExpect(status().isOk())
                .andExpect(content().string(containsString("[email protected]")));
    }

    @Test
    @WithUserDetails("[email protected]")
    public void givenBasicUser_whenGetFooSalute_thenForbidden() throws Exception
    {
        mockMvc.perform(MockMvcRequestBuilders.get("/foo/salute")
                .accept(MediaType.ALL))
                .andExpect(status().isForbidden());
    }
}

As you see we imported SpringSecurityWebAuxTestConfig to provide our users for testing. Each one used on its corresponding test case just by using a straightforward annotation, reducing code and complexity.

Better use @WithMockUser for simpler Role Based Security

As you see @WithUserDetails has all the flexibility you need for most of your applications. It allows you to use custom users with any GrantedAuthority, like roles or permissions. But if you are just working with roles, testing can be even easier and you could avoid constructing a custom UserDetailsService. In such cases, specify a simple combination of user, password and roles with @WithMockUser.

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@WithSecurityContext(
    factory = WithMockUserSecurityContextFactory.class
)
public @interface WithMockUser {
    String value() default "user";

    String username() default "";

    String[] roles() default {"USER"};

    String password() default "password";
}

The annotation defines default values for a very basic user. As in our case the route we are testing just requires that the authenticated user be a manager, we can quit using SpringSecurityWebAuxTestConfig and do this.

@Test
@WithMockUser(roles = "MANAGER")
public void givenManagerUser_whenGetFooSalute_thenOk() throws Exception
{
    mockMvc.perform(MockMvcRequestBuilders.get("/foo/salute")
            .accept(MediaType.ALL))
            .andExpect(status().isOk())
            .andExpect(content().string(containsString("user")));
}

Notice that now instead of the user [email protected] we are getting the default provided by @WithMockUser: user; yet it won't matter because what we really care about is his role: ROLE_MANAGER.

Conclusions

As you see with annotations like @WithUserDetails and @WithMockUser we can switch between different authenticated users scenarios without building classes alienated from our architecture just for making simple tests. Its also recommended you to see how @WithSecurityContext works for even more flexibility.

Clear text from textarea with selenium

Option a)

If you want to ensure keyboard events are fired, consider using sendKeys(CharSequence).

Example 1:

 from selenium.webdriver.common.keys import Keys
 # ...
 webElement.sendKeys(Keys.CONTROL + "a");
 webElement.sendKeys(Keys.DELETE);

Example 2:

 from selenium.webdriver.common.keys import Keys
 # ...
 webElement.sendKeys(Keys.BACK_SPACE); //do repeatedly, e.g. in while loop

WebElement

There are many ways to get the required WebElement, e.g.:

  • driver.find_element_by_id
  • driver.find_element_by_xpath
  • driver.find_element

Option b)

 webElement.clear();

If this element is a text entry element, this will clear the value.

Note that the events fired by this event may not be as you'd expect. In particular, we don't fire any keyboard or mouse events.

Targeting only Firefox with CSS

First of all, a disclaimer. I don't really advocate for the solution I present below. The only browser specific CSS I write is for IE (especially IE6), although I wish it wasn't the case.

Now, the solution. You asked it to be elegant so I don't know how elegant is it but it's sure going to target Gecko platforms only.

The trick is only working when JavaScript is enabled and makes use of Mozilla bindings (XBL), which are heavily used internally in Firefox and all other Gecko-based products. For a comparison, this is like the behavior CSS property in IE, but much more powerful.

Three files are involved in my solution:

  1. ff.html: the file to style
  2. ff.xml: the file containg the Gecko bindings
  3. ff.css: Firefox specific styling

ff.html

<!DOCTYPE html>

<html>
<head>
<style type="text/css">
body {
 -moz-binding: url(ff.xml#load-mozilla-css);
}
</style>
</head>
<body>

<h1>This should be red in FF</h1>

</body>
</html>

ff.xml

<?xml version="1.0"?>

<bindings xmlns="http://www.mozilla.org/xbl">
    <binding id="load-mozilla-css">
        <implementation>
            <constructor>
            <![CDATA[
                var link = document.createElement("link");
                    link.setAttribute("rel", "stylesheet");
                    link.setAttribute("type", "text/css");
                    link.setAttribute("href", "ff.css");

                document.getElementsByTagName("head")[0]
                        .appendChild(link);
            ]]>
            </constructor>
        </implementation>
    </binding>
</bindings>

ff.css

h1 {
 color: red;
}

Update: The above solution is not that good. It would be better if instead of appending a new LINK element it will add that "firefox" class on the BODY element. And it's possible, just by replacing the above JS with the following:

this.className += " firefox";

The solution is inspired by Dean Edwards' moz-behaviors.

What is simplest way to read a file into String?

Using Apache Commons IO.

import org.apache.commons.io.FileUtils;

//...

String contents = FileUtils.readFileToString(new File("/path/to/the/file"), "UTF-8")

You can see de javadoc for the method for details.

How to retrieve a user environment variable in CMake (Windows)

Getting variables into your CMake script

You can pass a variable on the line with the cmake invocation:

FOO=1 cmake

or by exporting a variable in BASH:

export FOO=1

Then you can pick it up in a cmake script using:

$ENV{FOO}

How to make a Java Generic method static?

I'll explain it in a simple way.

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

class Greet<T> {

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

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

class Greet<T> {

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

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

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

So, whenever you are calling the static method,

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

JVM interprets it as the following.

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

Both giving the same outputs.

Hello Bob
Hello 123

Oracle SQL - DATE greater than statement

As your query string is a literal, and assuming your dates are properly stored as DATE you should use date literals:

SELECT * FROM OrderArchive
WHERE OrderDate <= DATE '2015-12-31'

If you want to use TO_DATE (because, for example, your query value is not a literal), I suggest you to explicitly set the NLS_DATE_LANGUAGE parameter as you are using US abbreviated month names. That way, it won't break on some localized Oracle Installation:

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014', 'DD MON YYYY',
                           'NLS_DATE_LANGUAGE = American');

Remove duplicates from a list of objects based on property in Java 8

There are a lot of good answers here but I didn't find the one about using reduce method. So for your case, you can apply it in following way:

 List<Employee> employeeList = employees.stream()
      .reduce(new ArrayList<>(), (List<Employee> accumulator, Employee employee) ->
      {
        if (accumulator.stream().noneMatch(emp -> emp.getId().equals(employee.getId())))
        {
          accumulator.add(employee);
        }
        return accumulator;
      }, (acc1, acc2) ->
      {
        acc1.addAll(acc2);
        return acc1;
      });

How to pass a value from Vue data to href?

If you want to display links coming from your state or store in Vue 2.0, you can do like this:

<a v-bind:href="''"> {{ url_link }} </a>

How to replace a substring of a string

By regex i think this is java, the method replaceAll() returns a new String with the substrings replaced, so try this:

String teste = "abcd=0; efgh=1";

String teste2 = teste.replaceAll("abcd", "dddd");

System.out.println(teste2);

Output:

dddd=0; efgh=1

PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client

None of the answers here worked for me. What I had to do is:

  1. Re-run the installer.
  2. Select the quick action 're-configure' next to product 'MySQL Server'
  3. Go through the options till you reach Authentication Method and select 'Use Legacy Authentication Method'

After that it works fine.

How to pass boolean parameter value in pipeline to downstream jobs?

Jenkins "boolean" parameters are really just a shortcut for the "choice parameter" type with the choices hardcoded to the strings "true" and "false", and with a checkbox to set the string variable. But in the end, it is just that: a string variable, with nothing to do with a true boolean. That's why you need to convert the string to a boolean if you don't want to do a string comparison like:

if (myBoolean == "true")

Pass element ID to Javascript function

Check this: http://jsfiddle.net/h7kRt/1/,

you should change in jsfiddle on top-left to No-wrap in <head>

Your code looks good and it will work inside a normal page. In jsfiddle your function was being defined inside a load handler and thus is in a different scope. By changing to No-wrap you have it in the global scope and can use it as you wanted.

How to select into a variable in PL/SQL when the result might be null?

I know it's an old thread, but I still think it's worth to answer it.

select (
        SELECT COLUMN FROM MY_TABLE WHERE ....
        ) into v_column
from dual;

Example of use:

declare v_column VARCHAR2(100);
begin
  select (SELECT TABLE_NAME FROM ALL_TABLES WHERE TABLE_NAME = 'DOES NOT EXIST')
  into v_column 
  from dual;
  DBMS_OUTPUT.PUT_LINE('v_column=' || v_column);
end;

How to set the width of a RaisedButton in Flutter?

As said in documentation here

Raised buttons have a minimum size of 88.0 by 36.0 which can be overidden with ButtonTheme.

You can do it like that

ButtonTheme(
  minWidth: 200.0,
  height: 100.0,
  child: RaisedButton(
    onPressed: () {},
    child: Text("test"),
  ),
);

Ways to circumvent the same-origin policy

I can't claim credit for this image, but it matches everything I know on this subject and offers a bit of humor at the same time.

http://www.flickr.com/photos/iluvrhinestones/5889370258/

laravel 5.4 upload image

This code will store the image in database.

$('#image').change(function(){
        // FileReader function for read the file.
        let reader = new FileReader();
        var base64;
        reader.readAsDataURL(this.files[0]); 

        //Read File
        let filereader = new FileReader();
        var selectedFile = this.files[0];

        // Onload of file read the file content
        filereader.onload = function(fileLoadedEvent) {
            base64 = fileLoadedEvent.target.result;
            $("#pimage").val(JSON.stringify(base64));
        };

        filereader.readAsDataURL(selectedFile); 
 });

HTML content should be like this.

<div class="col-xs-12 col-sm-4 col-md-4 user_frm form-group">
        <input id="image" type="file" class="inputMaterial" name="image">        
        <input type="hidden" id="pimage" name="pimage" value="">
        <span class="bar"></span>
    </div>

Store image data in database like this:

//property_image longtext(database field type)

 $data= array(
      'property_image' => trim($request->get('pimage'),'"')
 );

Display image:

<img src="{{$result->property_image}}" >

Groovy method with optional parameters

Can't be done as it stands... The code

def myMethod(pParm1='1', pParm2='2'){
    println "${pParm1}${pParm2}"
}

Basically makes groovy create the following methods:

Object myMethod( pParm1, pParm2 ) {
    println "$pParm1$pParm2"
}

Object myMethod( pParm1 ) {
    this.myMethod( pParm1, '2' )
}

Object myMethod() {
    this.myMethod( '1', '2' )
}

One alternative would be to have an optional Map as the first param:

def myMethod( Map map = [:], String mandatory1, String mandatory2 ){
    println "${mandatory1} ${mandatory2} ${map.parm1 ?: '1'} ${map.parm2 ?: '2'}"
}

myMethod( 'a', 'b' )                // prints 'a b 1 2'
myMethod( 'a', 'b', parm1:'value' ) // prints 'a b value 2'
myMethod( 'a', 'b', parm2:'2nd')    // prints 'a b 1 2nd'

Obviously, documenting this so other people know what goes in the magical map and what the defaults are is left to the reader ;-)

How to find the mysql data directory from command line in windows

You can see the complete list of MySQL server options by running

mysqld --verbose --help

For example, to find out the path to the data directory on Linux, you can run:

mysqld --verbose --help | grep ^datadir

Example output:

datadir                                     /var/lib/mysql/

Best Practices for securing a REST API / web service

I searched a lot about restful ws security and we also ended up with using token via cookie from client to server to authenticate the requests . I used spring security for authorization of requests in service because I had to authenticate and authorized each request based on specified security policies that has already been in DB.

How to send a correct authorization header for basic authentication

If you are in a browser environment you can also use btoa.

btoa is a function which takes a string as argument and produces a Base64 encoded ASCII string. Its supported by 97% of browsers.

Example:

> "Basic " + btoa("billy"+":"+"secretpassword")
< "Basic YmlsbHk6c2VjcmV0cGFzc3dvcmQ="

You can then add Basic YmlsbHk6c2VjcmV0cGFzc3dvcmQ= to the authorization header.

Note that the usual caveats about HTTP BASIC auth apply, most importantly if you do not send your traffic over https an eavesdropped can simply decode the Base64 encoded string thus obtaining your password.

This security.stackexchange.com answer gives a good overview of some of the downsides.

What is a "web service" in plain English?

An operating system provides a GUI (and CLI) that you can interact with. It also provides an API that you can interact with programmatically.

Similarly, a website provides HTML pages that you can interact with and may also provide an API that offers the same information and operations programmatically. Or those services may only be available via an API with no associated user interface.

Kill a Process by Looking up the Port being used by it from a .BAT

Steps:

  1. Go to conf folder of your apache tomcat server. In my case,its apache-tomcat-7.0.61\conf as I am using apache-tomcat-7.0.61

  2. Open server.xml and change the port number from 8080 to any other port as your wish. For example:8081,8082,8087 etc

  3. Now go to bin folder and run shutdown.bat

  4. Now restart the server through eclipse.

Now your project will work without any interruption.

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

I use a for loop to iterate the string and use charAt() to get each character to examine it. Since the String is implemented with an array, the charAt() method is a constant time operation.

String s = "...stuff...";

for (int i = 0; i < s.length(); i++){
    char c = s.charAt(i);        
    //Process char
}

That's what I would do. It seems the easiest to me.

As far as correctness goes, I don't believe that exists here. It is all based on your personal style.

How to validate phone number in laravel 5.2?

I used the code below, and it works

'PHONE' => 'required|regex:/(0)[0-9]/|not_regex:/[a-z]/|min:9',

Form submit with AJAX passing form data to PHP without page refresh

<div class="container">
       <div class="row">
        <div class="col-md-3 col-sm-6 col-xs-12"></div>enter code here
          <div class="col-md-6 col-sm-6 col-xs-12">
          <div class="msg"></div>
            <form method="post" class="frm" id="form1" onsubmit="">
               <div class="form-group">
               <input type="text" class="form-control" name="fname" id="fname" placeholder="enter your first neme" required>
           <!--><span class="sp"><?php// echo $f_err;?></span><!-->
          </div>
        <div class="form-group">
               <input type="text" class="form-control" name="lname" id="lname" placeholder="enter your last neme" required>
              <!--><span class="sp"><?php// echo $l_err;?></span><!-->
             </div>
              <div class="form-group">
               <input type="text" class="form-control" name="email" id="email" placeholder="enter your email Address" required>
              <!--><span class="sp"><?php// echo $e_err;?></span><!-->
             </div>
             <div class="form-group">
               <input type="number" class="form-control" name="mno" id="mno" placeholder="enter your mobile number" required>
              <!--><span class="sp"><?php //echo $m_err;?></span><!-->
             </div>
              <div class="form-group">
               <input type="password" class="form-control" name="pass" id="pass" pattern="(?=.*[a-z])(?=.*[A-Z]).{4,8}" placeholder="enter your Password" required>
              <!--><span class="sp"><?php //echo $p_err;?></span><!-->
             </div>
              <div class="radio">
               &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" value="male" name="gender" id="gender" checked>male<br>
               &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" value="female" name="gender" id="gender">female<br>
               &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" value="other" name="gender" id="gender">other<br>
                                         <!--><span class="sp"> <?php //echo $r_err;?></span><!-->
             </div>
                <div class="checkbox">
                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" name="check" id="check" checked>I Agree Turms&Condition<br>
                   <!--><span class="sp"> <?php //echo $c_err;?></span><!-->
                 </div>
                 <input type="submit"  class="btn btn-warning" name="submit" id="submit">
             </form>enter code here

          </div>
               <div class="col-md-3 col-sm-6 col-xs-12"></div>
         </div> 

    </div>

How to keep footer at bottom of screen

What you’re looking for is the CSS Sticky Footer.

_x000D_
_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
html,_x000D_
body {_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
#wrap {_x000D_
  min-height: 100%;_x000D_
}_x000D_
_x000D_
#main {_x000D_
  overflow: auto;_x000D_
  padding-bottom: 180px;_x000D_
  /* must be same height as the footer */_x000D_
}_x000D_
_x000D_
#footer {_x000D_
  position: relative;_x000D_
  margin-top: -180px;_x000D_
  /* negative value of footer height */_x000D_
  height: 180px;_x000D_
  clear: both;_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* Opera Fix thanks to Maleika (Kohoutec) */_x000D_
_x000D_
body:before {_x000D_
  content: "";_x000D_
  height: 100%;_x000D_
  float: left;_x000D_
  width: 0;_x000D_
  margin-top: -32767px;_x000D_
  /* thank you Erik J - negate effect of float*/_x000D_
}
_x000D_
<div id="wrap">_x000D_
  <div id="main"></div>_x000D_
</div>_x000D_
_x000D_
<div id="footer"></div>
_x000D_
_x000D_
_x000D_

How can I read user input from the console?

I think there are some compiler errors.

  • Writeline should be WriteLine (capital 'L')
  • missing semicolon at the end of a line

        double a, b;
        Console.WriteLine("istenen sayiyi sonuna .00 koyarak yaz");
        a = double.Parse(Console.ReadLine());
        b = a * Math.PI; // Missing colon!
        Console.WriteLine("Sonuç " + b);
    

What is class="mb-0" in Bootstrap 4?

m - for classes that set margin, like this :

  • mt - for classes that set margin-top
  • mb - for classes that set margin-bottom
  • ml - for classes that set margin-left
  • mr - for classes that set margin-right
  • mx - for classes that set both margin-left and margin-right
  • my - for classes that set both margin-top and margin-bottom

Where size is one of margin :

  • 0 - for classes that eliminate the margin by setting it to 0, like mt-0
  • 1 - (by default) for classes that set the margin to $spacer * .25, like mt-1
  • 2 - (by default) for classes that set the margin to $spacer * .5, like mt-2
  • 3 - (by default) for classes that set the margin to $spacer, like mt-3
  • 4 - (by default) for classes that set the margin to $spacer * 1.5, like mt-4
  • 5 - (by default) for classes that set the margin to $spacer * 3, like mt-5
  • auto - for classes that set the margin to auto, like mx-auto

How to change package name of Android Project in Eclipse?

Just get Far Manager and search through for the old name. Then manually (in Far Manager) replace everywhere. Sadly, this is the only method that works in 100% of the possible cases.

How to remove empty cells in UITableView?

Implemented with swift on Xcode 6.1

self.tableView.tableFooterView = UIView(frame: CGRectZero)
self.tableView.tableFooterView?.hidden = true

The second line of code does not cause any effect on presentation, you can use to check if is hidden or not.

Answer taken from this link Fail to hide empty cells in UITableView Swift

Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

Tried couple of ways discussed above and end up with following working solution, just copy and paste in your editor to try. To test just change hash to inbox, outbox, compose in url and hit enter key.

<html>
    <head>
        <link type='text/css' rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css' />
        <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
    </head>
    <body>
        <div class="container body-content">
            <ul class="nav nav-tabs">
                <li class="active"><a data-toggle="tab" href="#inbox">Inbox</a></li>
                <li><a data-toggle="tab" href="#outbox">Outbox</a></li>
                <li><a data-toggle="tab" href="#compose">Compose</a></li>
            </ul>
            <div class="tab-content">
                <div id="inbox" class="tab-pane fade in active">
                    Inbox Content
                </div>
                <div id="outbox" class="tab-pane fade">
                    Outbox Content
                </div>
                <div id="compose" class="tab-pane fade">
                    Compose Content
                </div>
            </div>
        </div>
        <script>
            $(function () {
                var hash = window.location.hash;
                hash && $('ul.nav a[href="' + hash + '"]').tab('show');
            });
        </script>
    </body>
</html>

Hope this will save your time.

How to update a value, given a key in a hashmap?

Since I can't comment to a few answers due to less reputation, I will post a solution which I applied.

for(String key : someArray)
{
   if(hashMap.containsKey(key)//will check if a particular key exist or not 
   {
      hashMap.put(hashMap.get(key),value+1);// increment the value by 1 to an already existing key
   }
   else
   {
      hashMap.put(key,value);// make a new entry into the hashmap
   }
}

How do I make Java register a string input with spaces?

Since it's a long time and people keep suggesting to use Scanner#nextLine(), there's another chance that Scanner can take spaces included in input.

Class Scanner

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

You can use Scanner#useDelimiter() to change the delimiter of Scanner to another pattern such as a line feed or something else.

Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;

System.out.println("Please input question:");
question = in.next();

// TODO do something with your input such as removing spaces...

if (question.equalsIgnoreCase("howdoyoulikeschool?") )
    /* it seems strings do not allow for spaces */
    System.out.println("CLOSED!!");
else
    System.out.println("Que?");

Why doesn't Java offer operator overloading?

I think this may have been a conscious design choice to force developers to create functions whose names clearly communicate their intentions. In C++ developers would overload operators with functionality that would often have no relation to the commonly accepted nature of the given operator, making it nearly impossible to determine what a piece of code does without looking at the definition of the operator.

__init__ and arguments in Python

The fact that your method does not use the self argument (which is a reference to the instance that the method is attached to) doesn't mean you can leave it out. It always has to be there, because Python is always going to try to pass it in.

Searching word in vim?

If you are working in Ubuntu,follow the steps:

  1. Press / and type word to search
  2. To search in forward press 'SHIFT' key with * key
  3. To search in backward press 'SHIFT' key with # key

iPhone Debugging: How to resolve 'failed to get the task for process'?

The ad-hoc profile doesn't support debugging. You need to debug with a Development profile, and use the Ad-Hoc profile only for distributing non-debuggable copies.

XSS filtering function in PHP

Try using for Clean XSS

xss_clean($data): "><script>alert(String.fromCharCode(74,111,104,116,111,32,82,111,98,98,105,101))</script>

Swift: How to get substring from start to last index of character

Here is a simple way to get substring in Swift

import UIKit

var str = "Hello, playground" 
var res = NSString(string: str)
print(res.substring(from: 4))
print(res.substring(to: 10))

How to post data using HttpClient?

You need to use:

await client.PostAsync(uri, content);

Something like that:

var comment = "hello world";
var questionId = 1;

var formContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("comment", comment), 
    new KeyValuePair<string, string>("questionId", questionId) 
});

var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);

And if you need to get the response after post, you should use:

var stringContent = await response.Content.ReadAsStringAsync();

Hope it helps ;)

For-loop vs while loop in R

Because 1 is numeric, but not integer (i.e. it's a floating point number), and 1:6000 is numeric and integer.

> print(class(1))
[1] "numeric"
> print(class(1:60000))
[1] "integer"

60000 squared is 3.6 billion, which is NOT representable in signed 32-bit integer, hence you get an overflow error:

> as.integer(60000)*as.integer(60000)
[1] NA
Warning message:
In as.integer(60000) * as.integer(60000) : NAs produced by integer overflow

3.6 billion is easily representable in floating point, however:

> as.single(60000)*as.single(60000)
[1] 3.6e+09

To fix your for code, convert to a floating point representation:

function (N)
{
    for(i in as.single(1:N)) {
        y <- i*i
    }
}

What is an unhandled promise rejection?

Try not closing the connection before you send data to your database. Remove client.close(); from your code and it'll work fine.

PHP Array to CSV

It worked for me.

 $f=fopen('php://memory','w');
 $header=array("asdf ","asdf","asd","Calasdflee","Start Time","End Time" );      
 fputcsv($f,$header);
 fputcsv($f,$header);
 fputcsv($f,$header); 
 fseek($f,0);
 header('content-type:text/csv'); 
 header('Content-Disposition: attachment; filename="' . $filename . '";');
 fpassthru($f);```

syntax error near unexpected token `('

Try

sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)

How can I get a specific field of a csv file?

import csv
mycsv = csv.reader(open(myfilepath))
for row in mycsv:
   text = row[1]

Following the comments to the SO question here, a best, more robust code would be:

import csv
with open(myfilepath, 'rb') as f:
    mycsv = csv.reader(f)
    for row in mycsv:
        text = row[1]
        ............

Update: If what the OP actually wants is the last string in the last row of the csv file, there are several aproaches that not necesarily needs csv. For example,

fulltxt = open(mifilepath, 'rb').read()
laststring = fulltxt.split(',')[-1]

This is not good for very big files because you load the complete text in memory but could be ok for small files. Note that laststring could include a newline character so strip it before use.

And finally if what the OP wants is the second string in line n (for n=2):

Update 2: This is now the same code than the one in the answer from J.F.Sebastian. (The credit is for him):

import csv
line_number = 2     
with open(myfilepath, 'rb') as f:
    mycsv = csv.reader(f)
    mycsv = list(mycsv)
    text = mycsv[line_number][1]
    ............

How to submit http form using C#

Response.Write("<script> try {this.submit();} catch(e){} </script>");

SQL GROUP BY CASE statement with aggregate function

I think the answer is pretty simple (unless I'm missing something?)

SELECT    
CASE
    WHEN col1 > col2 THEN SUM(col3*col4)
    ELSE 0
END AS some_product
FROM some_table
GROUP BY
CASE
    WHEN col1 > col2 THEN SUM(col3*col4)
    ELSE 0
END

You can put the CASE STATEMENT in the GROUP BY verbatim (minus the alias column name)

How to tell Maven to disregard SSL errors (and trusting all certs)?

You can disable SSL certificate checking by adding one or more of these command line parameters:

  • -Dmaven.wagon.http.ssl.insecure=true - enable use of relaxed SSL check for user generated certificates.
  • -Dmaven.wagon.http.ssl.allowall=true - enable match of the server's X.509 certificate with hostname. If disabled, a browser like check will be used.
  • -Dmaven.wagon.http.ssl.ignore.validity.dates=true - ignore issues with certificate dates.

Official documentation: http://maven.apache.org/wagon/wagon-providers/wagon-http/

Here's the oneliner for an easy copy-and-paste:

-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true

Ajay Gautam suggested that you could also add the above to the ~/.mavenrc file as not to have to specify it every time at command line:

$ cat ~/.mavenrc 
MAVEN_OPTS="-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true"

Http Get using Android HttpURLConnection

Here is a complete AsyncTask class

public class GetMethodDemo extends AsyncTask<String , Void ,String> {
    String server_response;

    @Override
    protected String doInBackground(String... strings) {

        URL url;
        HttpURLConnection urlConnection = null;

        try {
            url = new URL(strings[0]);
            urlConnection = (HttpURLConnection) url.openConnection();

            int responseCode = urlConnection.getResponseCode();

            if(responseCode == HttpURLConnection.HTTP_OK){
                server_response = readStream(urlConnection.getInputStream());
                Log.v("CatalogClient", server_response);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        Log.e("Response", "" + server_response);


    }
}

// Converting InputStream to String

private String readStream(InputStream in) {
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return response.toString();
    }

To Call this AsyncTask class

new GetMethodDemo().execute("your web-service url");

Ignore invalid self-signed ssl certificate in node.js with https.request?

In your request options, try including the following:

   var req = https.request({ 
      host: '192.168.1.1', 
      port: 443,
      path: '/',
      method: 'GET',
      rejectUnauthorized: false,
      requestCert: true,
      agent: false
    },

how to read all files inside particular folder

using System.IO;
...
foreach (string file in Directory.EnumerateFiles(folderPath, "*.xml"))
{
    string contents = File.ReadAllText(file);
}

Note the above uses a .NET 4.0 feature; in previous versions replace EnumerateFiles with GetFiles). Also, replace File.ReadAllText with your preferred way of reading xml files - perhaps XDocument, XmlDocument or an XmlReader.

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

Use xml.etree.ElementTree to print nicely formatted xml files

You can use the function toprettyxml() from xml.dom.minidom in order to do that:

def prettify(elem):
    """Return a pretty-printed XML string for the Element.
    """
    rough_string = ElementTree.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="\t")

The idea is to print your Element in a string, parse it using minidom and convert it again in XML using the toprettyxml function.

Source: http://pymotw.com/2/xml/etree/ElementTree/create.html

What is the best way to left align and right align two div tags?

This solution has left aligned text and button on the far right.

If anyone is looking for a material design answer:

<div layout="column" layout-align="start start">
 <div layout="row" style="width:100%">
    <div flex="grow">Left Aligned text</div>
    <md-button aria-label="help" ng-click="showHelpDialog()">
      <md-icon md-svg-icon="help"></md-icon>
    </md-button>
 </div>
</div>  

Choosing line type and color in Gnuplot 4.0

Edit: Sorry, this won't work for you. I just remembered the line color thing is in 4.2. I ran into this problem in the past and my fix was to upgrade gnuplot.

You can control the color with set style line as well. "lt 3" will give you a dashed line while "lt 1" will give you a solid line. To add color, you can use "lc rgb 'color'". This should do what you need:


set style line 1 lt 1 lw 3 pt 3 lc rgb "red"
set style line 2 lt 3 lw 3 pt 3 lc rgb "red"
set style line 3 lt 1 lw 3 pt 3 lc rgb "blue"
set style line 4 lt 3 lw 3 pt 3 lc rgb "blue"

How to get a view table query (code) in SQL Server 2008 Management Studio

Use sp_helptext before the view_name. Example:

sp_helptext Example_1

Hence you will get the query:

CREATE VIEW dbo.Example_1
AS
SELECT       a, b, c
FROM         dbo.table_name JOIN blah blah blah
WHERE        blah blah blah

sp_helptext will give stored procedures.

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

Another reason why an undefined index notice will be thrown, would be that a column was omitted from a database query.

I.e.:

$query = "SELECT col1 FROM table WHERE col_x = ?";

Then trying to access more columns/rows inside a loop.

I.e.:

print_r($row['col1']);
print_r($row['col2']); // undefined index thrown

or in a while loop:

while( $row = fetching_function($query) ) {

    echo $row['col1'];
    echo "<br>";
    echo $row['col2']; // undefined index thrown
    echo "<br>";
    echo $row['col3']; // undefined index thrown

}

Something else that needs to be noted is that on a *NIX OS and Mac OS X, things are case-sensitive.

Consult the followning Q&A's on Stack:

Convert date to UTC using moment.js

moment.utc(date).format(...); 

is the way to go, since

moment().utc(date).format(...);

does behave weird...

What is the purpose of meshgrid in Python / NumPy?

Basic Idea

Given possible x values, xs, (think of them as the tick-marks on the x-axis of a plot) and possible y values, ys, meshgrid generates the corresponding set of (x, y) grid points---analogous to set((x, y) for x in xs for y in yx). For example, if xs=[1,2,3] and ys=[4,5,6], we'd get the set of coordinates {(1,4), (2,4), (3,4), (1,5), (2,5), (3,5), (1,6), (2,6), (3,6)}.

Form of the Return Value

However, the representation that meshgrid returns is different from the above expression in two ways:

First, meshgrid lays out the grid points in a 2d array: rows correspond to different y-values, columns correspond to different x-values---as in list(list((x, y) for x in xs) for y in ys), which would give the following array:

   [[(1,4), (2,4), (3,4)],
    [(1,5), (2,5), (3,5)],
    [(1,6), (2,6), (3,6)]]

Second, meshgrid returns the x and y coordinates separately (i.e. in two different numpy 2d arrays):

   xcoords, ycoords = (
       array([[1, 2, 3],
              [1, 2, 3],
              [1, 2, 3]]),
       array([[4, 4, 4],
              [5, 5, 5],
              [6, 6, 6]]))
   # same thing using np.meshgrid:
   xcoords, ycoords = np.meshgrid([1,2,3], [4,5,6])
   # same thing without meshgrid:
   xcoords = np.array([xs] * len(ys)
   ycoords = np.array([ys] * len(xs)).T

Note, np.meshgrid can also generate grids for higher dimensions. Given xs, ys, and zs, you'd get back xcoords, ycoords, zcoords as 3d arrays. meshgrid also supports reverse ordering of the dimensions as well as sparse representation of the result.

Applications

Why would we want this form of output?

Apply a function at every point on a grid: One motivation is that binary operators like (+, -, *, /, **) are overloaded for numpy arrays as elementwise operations. This means that if I have a function def f(x, y): return (x - y) ** 2 that works on two scalars, I can also apply it on two numpy arrays to get an array of elementwise results: e.g. f(xcoords, ycoords) or f(*np.meshgrid(xs, ys)) gives the following on the above example:

array([[ 9,  4,  1],
       [16,  9,  4],
       [25, 16,  9]])

Higher dimensional outer product: I'm not sure how efficient this is, but you can get high-dimensional outer products this way: np.prod(np.meshgrid([1,2,3], [1,2], [1,2,3,4]), axis=0).

Contour plots in matplotlib: I came across meshgrid when investigating drawing contour plots with matplotlib for plotting decision boundaries. For this, you generate a grid with meshgrid, evaluate the function at each grid point (e.g. as shown above), and then pass the xcoords, ycoords, and computed f-values (i.e. zcoords) into the contourf function.

anaconda - graphviz - can't import after installation

To install graphviz,

conda install -c anaconda graphviz
pip install graphviz

If conda command not found. Follow these:

export PATH=~/anaconda/bin:$PATH
conda --version # to check your conda version

Difference between conda and pip installation,
refer this stackoverflow answer

Run Command Prompt Commands

Yes, there is (see link in Matt Hamilton's comment), but it would be easier and better to use .NET's IO classes. You can use File.ReadAllBytes to read the files and then File.WriteAllBytes to write the "embedded" version.

How to completely uninstall Android Studio on Mac?

I was also facing same kind of problem on my Macbook Pro. I took these very simple steps and freshly installed Android Studio.

** Link Contains Images, look if facing any problem.

These Very Simple Steps Can Solve Your Problem.

  1. Type "Command+option+Space Bar"
  2. Type "Android Studio"
  3. Click '+' button just below search box. image
  4. A new bar will come up "Kind" is "any" click on "kind" --> Others --> search for "system file" and select that by putting a tick mark.! And click on Ok. image
  5. Then select "are included" from the drop down menu !
  6. Then you get a lot of system file that need to be deleted to complete the fully un-installation of any app.
  7. Click "command+A" to select all files and take a look on the file remove is some video files are also included. And click "command + Delete"
  8. Empty your trash. Done

How to select Python version in PyCharm?

Go to:

Files -> Settings -> Project -> *"Your Project Name"* -> Project Interpreter

There you can see which external libraries you have installed for python2 and which for python3.

Select the required python version according to your requirements.

Image

Floating point inaccuracy examples

A cute piece of numerical weirdness may be observed if one converts 9999999.4999999999 to a float and back to a double. The result is reported as 10000000, even though that value is obviously closer to 9999999, and even though 9999999.499999999 correctly rounds to 9999999.

HTML 5 Geo Location Prompt in Chrome

For an easy workaround, just copy the HTML file to some cloud share, such as Dropbox, and use the shared link in your browser. Easy.

How to install multiple python packages at once using pip

You can use the following steps:

Step 1: Create a requirements.txt with list of packages to be installed. If you want to copy packages in a particular environment, do this

pip freeze >> requirements.txt

else store package names in a file named requirements.txt

Step 2: Execute pip command with this file

pip install -r requirements.txt

Bootstrap visible and hidden classes not working properly

No CSS required, visible class should like this: visible-md-block not just visible-md and the code should be like this:

<div class="containerdiv hidden-sm hidden-xs visible-md-block visible-lg-block">
    <div class="row">
        <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 logo">

        </div>
    </div>
</div>

<div class="mobile hidden-md hidden-lg ">
    test
</div>

Extra css is not required at all.

Removing duplicates from a SQL query (not just "use distinct")

You need to tell the query what value to pick for the other columns, MIN or MAX seem like suitable choices.

 SELECT
   U.NAME, MIN(P.PIC_ID)
 FROM
   USERS U,
   PICTURES P,
   POSTINGS P1
 WHERE
   U.EMAIL_ID = P1.EMAIL_ID AND
   P1.PIC_ID = P.PIC_ID AND
   P.CAPTION LIKE '%car%'
 GROUP BY
   U.NAME;

Passing multiple parameters with $.ajax url

why not just pass an data an object with your key/value pairs then you don't have to worry about encoding

$.ajax({
    type: "Post",
    url: "getdata.php",
    data:{
       timestamp: timestamp,
       uid: id,
       uname: name
    },
    async: true,
    cache: false,
    success: function(data) {


    };
}?);?

Javascript/Jquery to change class onclick?

Another example is:

$(".myClass").on("click", function () {
   var $this = $(this);

   if ($this.hasClass("show") {
    $this.removeClass("show");
   } else {
    $this.addClass("show");
   }
});

Python Save to file

myFile = open('today','r')

ips = {}

for line in myFile:
    parts = line.split()
    if parts[1] == 'Failure':
        ips.setdefault(parts[0], 0)
        ips[parts[0]] += 1

of = open('failed.py', 'w')
for ip in [k for k, v in ips.iteritems() if v >=5]:
    of.write(k+'\n')

Check out setdefault, it makes the code a little more legible. Then you dump your data with the file object's write method.

Writing files in Node.js

You can write to files with streams.

Just do it like this:

const fs = require('fs');

const stream = fs.createWriteStream('./test.txt');
stream.write("Example text");

Unmount the directory which is mounted by sshfs in Mac

sudo diskutil unmount force PATH 

Works every time :)
Notice the force tag

How to update npm

npm i -g npm

      Update available 4.5.0 ? 4.6.1    ¦
   ¦     Run npm i -g npm to update 

this is what npm recommends when in terminal, second piece is directly copied and pasted from my terminal

note: im using a mac

How do I clone a github project to run locally?

git clone git://github.com/ryanb/railscasts-episodes.git

How much data can a List can hold at the maximum?

The interface however defines the size() method, which returns an int.

Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

So, no limit, but after you reach Integer.MAX_VALUE, the behaviour of the list changes a bit

ArrayList (which is tagged) is backed by an array, and is limited to the size of the array - i.e. Integer.MAX_VALUE

Why won't eclipse switch the compiler to Java 8?

First of all you should get JdK 8.

if you have Jdk installed.

you should set its path using cmd prompt or system variables.

sometimes it can happen that the path is not set due to which eclipse is unable to get the properties for jdk.

Installing latest ecipse luna can solve your problem.

i have indigo and luna. i can set 1.8 in luna but 1.7 in indigo.Eclipse luna

You can check the eclipse site. it says that the eclipse luna was certainly to associate the properties for jdk 8.

figure of imshow() is too small

I'm new to python too. Here is something that looks like will do what you want to

axes([0.08, 0.08, 0.94-0.08, 0.94-0.08]) #[left, bottom, width, height]
axis('scaled')`

I believe this decides the size of the canvas.

JPanel setBackground(Color.BLACK) does nothing

You have to call the super.paintComponent(); as well, to allow the Java API draw the original background. The super refers to the original JPanel code.

public void paintComponent(Graphics g){
    super.paintComponent(g);

    g.setColor(Color.red);
    g.fillOval(player.getxCenter(), player.getyCenter(), player.getRadius(), player.getRadius());
}

How can I replace non-printable Unicode characters in Java?

I have redesigned the code for phone numbers +9 (987) 124124 Extract digits from a string in Java

 public static String stripNonDigitsV2( CharSequence input ) {
    if (input == null)
        return null;
    if ( input.length() == 0 )
        return "";

    char[] result = new char[input.length()];
    int cursor = 0;
    CharBuffer buffer = CharBuffer.wrap( input );
    int i=0;
    while ( i< buffer.length()  ) { //buffer.hasRemaining()
        char chr = buffer.get(i);
        if (chr=='u'){
            i=i+5;
            chr=buffer.get(i);
        }

        if ( chr > 39 && chr < 58 )
            result[cursor++] = chr;
        i=i+1;
    }

    return new String( result, 0, cursor );
}

How to display gpg key details without importing it?

There are several detail levels you can get when looking at OpenPGP key data: a basic summary, a machine-readable output of this summary or a detailed (and very technical) list of the individual OpenPGP packets.

Basic Key Information

For a brief peak at an OpenPGP key file, you can simply pass the filename as parameter or pipe in the key data through STDIN. If no command is passed, GnuPG tries to guess what you want to do -- and for key data, this is printing a summary on the key:

$ gpg a4ff2279.asc
gpg: WARNING: no command supplied.  Trying to guess what you mean ...
pub   rsa8192 2012-12-25 [SC]
      0D69E11F12BDBA077B3726AB4E1F799AA4FF2279
uid           Jens Erat (born 1988-01-19 in Stuttgart, Germany)
uid           Jens Erat <[email protected]>
uid           Jens Erat <[email protected]>
uid           Jens Erat <[email protected]>
uid           Jens Erat <[email protected]>
uid           [jpeg image of size 12899]
sub   rsa4096 2012-12-26 [E] [revoked: 2014-03-26]
sub   rsa4096 2012-12-26 [S] [revoked: 2014-03-26]
sub   rsa2048 2013-01-23 [S] [expires: 2023-01-21]
sub   rsa2048 2013-01-23 [E] [expires: 2023-01-21]
sub   rsa4096 2014-03-26 [S] [expires: 2020-09-03]
sub   rsa4096 2014-03-26 [E] [expires: 2020-09-03]
sub   rsa4096 2014-11-22 [A] [revoked: 2016-03-01]
sub   rsa4096 2016-02-24 [A] [expires: 2020-02-23]

By setting --keyid-format 0xlong, long key IDs are printed instead of the insecure short key IDs:

$ gpg a4ff2279.asc                                                                 
gpg: WARNING: no command supplied.  Trying to guess what you mean ...
pub   rsa8192/0x4E1F799AA4FF2279 2012-12-25 [SC]
      0D69E11F12BDBA077B3726AB4E1F799AA4FF2279
uid                             Jens Erat (born 1988-01-19 in Stuttgart, Germany)
uid                             Jens Erat <[email protected]>
uid                             Jens Erat <[email protected]>
uid                             Jens Erat <[email protected]>
uid                             Jens Erat <[email protected]>
uid                             [jpeg image of size 12899]
sub   rsa4096/0x0F3ED8E6759A536E 2012-12-26 [E] [revoked: 2014-03-26]
sub   rsa4096/0x2D6761A7CC85941A 2012-12-26 [S] [revoked: 2014-03-26]
sub   rsa2048/0x9FF7E53ACB4BD3EE 2013-01-23 [S] [expires: 2023-01-21]
sub   rsa2048/0x5C88F5D83E2554DF 2013-01-23 [E] [expires: 2023-01-21]
sub   rsa4096/0x8E78E44DFB1B55E9 2014-03-26 [S] [expires: 2020-09-03]
sub   rsa4096/0xCC73B287A4388025 2014-03-26 [E] [expires: 2020-09-03]
sub   rsa4096/0x382D23D4C9773A5C 2014-11-22 [A] [revoked: 2016-03-01]
sub   rsa4096/0xFF37A70EDCBB4926 2016-02-24 [A] [expires: 2020-02-23]
pub   rsa1024/0x7F60B22EA4FF2279 2014-06-16 [SCEA] [revoked: 2016-08-16]

Providing -v or -vv will even add some more information. I prefer printing the package details in this case, though (see below).

Machine-Readable Output

GnuPG also has a colon-separated output format, which is easily parsable and has a stable format. The format is documented in GnuPG doc/DETAILS file. The option to receive this format is --with-colons.

$ gpg --with-colons a4ff2279.asc
gpg: WARNING: no command supplied.  Trying to guess what you mean ...
pub:-:8192:1:4E1F799AA4FF2279:1356475387:::-:
uid:::::::::Jens Erat (born 1988-01-19 in Stuttgart, Germany):
uid:::::::::Jens Erat <[email protected]>:
uid:::::::::Jens Erat <[email protected]>:
uid:::::::::Jens Erat <[email protected]>:
uid:::::::::Jens Erat <[email protected]>:
uat:::::::::1 12921:
sub:-:4096:1:0F3ED8E6759A536E:1356517233:1482747633:::
sub:-:4096:1:2D6761A7CC85941A:1356517456:1482747856:::
sub:-:2048:1:9FF7E53ACB4BD3EE:1358985314:1674345314:::
sub:-:2048:1:5C88F5D83E2554DF:1358985467:1674345467:::
sub:-:4096:1:8E78E44DFB1B55E9:1395870592:1599164118:::
sub:-:4096:1:CC73B287A4388025:1395870720:1599164118:::
sub:-:4096:1:382D23D4C9773A5C:1416680427:1479752427:::
sub:-:4096:1:FF37A70EDCBB4926:1456322829:1582466829:::

Since GnuPG 2.1.23, the gpg: WARNING: no command supplied. Trying to guess what you mean ... warning can be omitted by using the --import-options show-only option together with the --import command (this also works without --with-colons, of course):

$ gpg --with-colons --import-options show-only --import a4ff2279
[snip]

For older versions: the warning message is printed on STDERR, so you could just read STDIN to split apart the key information from the warning.

Technical Details: Listing OpenPGP Packets

Without installing any further packages, you can use gpg --list-packets [file] to view information on the OpenPGP packets contained in the file.

$ gpg --list-packets a4ff2279.asc
:public key packet:
    version 4, algo 1, created 1356475387, expires 0
    pkey[0]: [8192 bits]
    pkey[1]: [17 bits]
    keyid: 4E1F799AA4FF2279
:user ID packet: "Jens Erat (born 1988-01-19 in Stuttgart, Germany)"
:signature packet: algo 1, keyid 4E1F799AA4FF2279
    version 4, created 1356516623, md5len 0, sigclass 0x13
    digest algo 2, begin of digest 18 46
    hashed subpkt 27 len 1 (key flags: 03)
[snip]

The pgpdump [file] tool works similar to gpg --list-packets and provides a similar output, but resolves all those algorithm identifiers to readable representations. It is available for probably all relevant distributions (on Debian derivatives, the package is called pgpdump like the tool itself).

$ pgpdump a4ff2279.asc
Old: Public Key Packet(tag 6)(1037 bytes)
    Ver 4 - new
    Public key creation time - Tue Dec 25 23:43:07 CET 2012
    Pub alg - RSA Encrypt or Sign(pub 1)
    RSA n(8192 bits) - ...
    RSA e(17 bits) - ...
Old: User ID Packet(tag 13)(49 bytes)
    User ID - Jens Erat (born 1988-01-19 in Stuttgart, Germany)
Old: Signature Packet(tag 2)(1083 bytes)
    Ver 4 - new
    Sig type - Positive certification of a User ID and Public Key packet(0x13).
    Pub alg - RSA Encrypt or Sign(pub 1)
    Hash alg - SHA1(hash 2)
    Hashed Sub: key flags(sub 27)(1 bytes)
[snip]

jQuery: How can I create a simple overlay?

Here is a simple javascript only solution

function displayOverlay(text) {
    $("<table id='overlay'><tbody><tr><td>" + text + "</td></tr></tbody></table>").css({
        "position": "fixed",
        "top": 0,
        "left": 0,
        "width": "100%",
        "height": "100%",
        "background-color": "rgba(0,0,0,.5)",
        "z-index": 10000,
        "vertical-align": "middle",
        "text-align": "center",
        "color": "#fff",
        "font-size": "30px",
        "font-weight": "bold",
        "cursor": "wait"
    }).appendTo("body");
}

function removeOverlay() {
    $("#overlay").remove();
}

Demo:

http://jsfiddle.net/UziTech/9g0pko97/

Gist:

https://gist.github.com/UziTech/7edcaef02afa9734e8f2

How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds?

I think I have a better answer.

new Timestamp(longEpochTime).toLocalDateTime();

How to bind 'touchstart' and 'click' events but not respond to both?

This hasn't been mentioned here, but you may want to check out this link: https://joshtronic.com/2015/04/19/handling-click-and-touch-events-on-the-same-element/

To recap for posterity, instead of trying to assign to both handlers and then sort out the result, you can simply check if the device is a touchscreen or not and only assign to the relevant event. Observe:

var clickEvent = (function() {
  if ('ontouchstart' in document.documentElement === true)
    return 'touchstart';
  else
    return 'click';
})();

// and assign thusly:

el.addEventListener( clickEvent, function( e ){ 
    // things and stuff
});

I am using this to bind my events so that I can test on touchscreens that handle both touchstart and click events which would fire twice, and on my development PC which only hears the click

One problem the author of that link mentions though, is touchscreen laptops designed to handle both events:

I learned about a third device I was not considering, the touchscreen laptop. It’s a hybrid device that supports both touch and click events. Binding one event means only that event be supported. Does that mean someone with a touchscreen and mouse would have to explicitly touch because that’s the only event I am handling?

Binding touchstart and click seemed ideal to handle these hybrid devices. To keep the event from firing twice, I added e.stopPropagation() and e.preventDefault() to the callback functions. e.stopPropagation() stops events from “bubbling up” to their parents but also keeps a second event from firing. I included e.preventDefault() as a “just in case” but seems like it could be omitted.

How do I get started with Node.js

You can follow these tutorials to get started

Tutorials

Developer Sites

Videos

Screencasts

Books

Courses

Blogs

Podcasts

JavaScript resources

Node.js Modules

Other

What is the difference between display: inline and display: inline-block?

splattne's answer probably covered most of everything so I won't repeat the same thing, but: inline and inline-block behave differently with the direction CSS property.

Within the next snippet you see one two (in order) is rendered, like it does in LTR layouts. I suspect the browser here auto-detected the English part as LTR text and rendered it from left to right.

_x000D_
_x000D_
body {_x000D_
  text-align: right;_x000D_
  direction: rtl;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
  display: block; /* just being explicit */_x000D_
}_x000D_
_x000D_
span {_x000D_
  display: inline;_x000D_
}
_x000D_
<h2>_x000D_
  ??? ????? ????_x000D_
  <span>one</span>_x000D_
  <span>two</span>_x000D_
</h2>
_x000D_
_x000D_
_x000D_

However, if I go ahead and set display to inline-block, the browser appears to respect the direction property and render the elements from right to left in order, so that two one is rendered.

_x000D_
_x000D_
body {_x000D_
  text-align: right;_x000D_
  direction: rtl;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
  display: block; /* just being explicit */_x000D_
}_x000D_
_x000D_
span {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<h2>_x000D_
  ??? ????? ????_x000D_
  <span>one</span>_x000D_
  <span>two</span>_x000D_
</h2>
_x000D_
_x000D_
_x000D_

I don't know if there are any other quirks to this, I only found about this empirically on Chrome.

What's the difference between a 302 and a 307 redirect?

A good example of the 307 Internal Redirect in action is when Google Chrome encounters a HTTP call to a domain it knows as requiring Strict Transport Security.

The browser redirects seamlessly, using the same method as the original call.

HTST 307 Internal Redirect

Multiple Indexes vs Multi-Column Indexes

One item that seems to have been missed is star transformations. Index Intersection operators resolve the predicate by calculating the set of rows hit by each of the predicates before any I/O is done on the fact table. On a star schema you would index each individual dimension key and the query optimiser can resolve which rows to select by the index intersection computation. The indexes on individual columns give the best flexibility for this.

Removing special characters VBA Excel

This is what I use, based on this link

Function StripAccentb(RA As Range)

Dim A As String * 1
Dim B As String * 1
Dim i As Integer
Dim S As String
'Const AccChars = "ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöùúûüýÿ"
'Const RegChars = "SZszYAAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaceeeeiiiidnooooouuuuyy"
Const AccChars = "ñéúãíçóêôöá" ' using less characters is faster
Const RegChars = "neuaicoeooa"
S = RA.Cells.Text
For i = 1 To Len(AccChars)
A = Mid(AccChars, i, 1)
B = Mid(RegChars, i, 1)
S = Replace(S, A, B)
'Debug.Print (S)
Next


StripAccentb = S

Exit Function
End Function

Usage:

=StripAccentb(B2) ' cell address

Sub version for all cells in a sheet:

Sub replacesub()
Dim A As String * 1
Dim B As String * 1
Dim i As Integer
Dim S As String
Const AccChars = "ñéúãíçóêôöá" ' using less characters is faster
Const RegChars = "neuaicoeooa"
Range("A1").Resize(Cells.Find(what:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row, _
Cells.Find(what:="*", SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Column).Select '
For Each cell In Selection
If cell <> "" Then
S = cell.Text
    For i = 1 To Len(AccChars)
    A = Mid(AccChars, i, 1)
    B = Mid(RegChars, i, 1)
    S = replace(S, A, B)
    Next
cell.Value = S
Debug.Print "celltext "; (cell.Text)
End If
Next cell
End Sub

How to convert a plain object into an ES6 Map?

ES6

convert object to map:

const objToMap = (o) => new Map(Object.entries(o));

convert map to object:

const mapToObj = (m) => [...m].reduce( (o,v)=>{ o[v[0]] = v[1]; return o; },{} )

Note: the mapToObj function assumes map keys are strings (will fail otherwise)

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

How should I escape commas and speech marks in CSV files so they work in Excel?

Single quotes work fine too, even without escaping the double quotes, at least in Excel 2016:

'text with spaces, and a comma','more text with spaces','spaces and "quoted text" and more spaces','nospaces','NOSPACES1234'

Excel will put that in 5 columns (if you choose the single quote as "Text qualifier" in the "Text to columns" wizard)

Playing .mp3 and .wav in Java?

I would recommend using the BasicPlayerAPI. It's open source, very simple and it doesn't require JavaFX. http://www.javazoom.net/jlgui/api.html

After downloading and extracting the zip-file one should add the following jar-files to the build path of the project:

  • basicplayer3.0.jar
  • all the jars from the lib directory (inside BasicPlayer3.0)

Here is a minimalistic usage example:

String songName = "HungryKidsofHungary-ScatteredDiamonds.mp3";
String pathToMp3 = System.getProperty("user.dir") +"/"+ songName;
BasicPlayer player = new BasicPlayer();
try {
    player.open(new URL("file:///" + pathToMp3));
    player.play();
} catch (BasicPlayerException | MalformedURLException e) {
    e.printStackTrace();
}

Required imports:

import java.net.MalformedURLException;
import java.net.URL;
import javazoom.jlgui.basicplayer.BasicPlayer;
import javazoom.jlgui.basicplayer.BasicPlayerException;

That's all you need to start playing music. The Player is starting and managing his own playback thread and provides play, pause, resume, stop and seek functionality.

For a more advanced usage you may take a look at the jlGui Music Player. It's an open source WinAmp clone: http://www.javazoom.net/jlgui/jlgui.html

The first class to look at would be PlayerUI (inside the package javazoom.jlgui.player.amp). It demonstrates the advanced features of the BasicPlayer pretty well.

Delete all rows with timestamp older than x days

DELETE FROM on_search 
WHERE search_date < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 180 DAY))

VBA check if file exists

I use this function to check for file existence:

Function IsFile(ByVal fName As String) As Boolean
'Returns TRUE if the provided name points to an existing file.
'Returns FALSE if not existing, or if it's a folder
    On Error Resume Next
    IsFile = ((GetAttr(fName) And vbDirectory) <> vbDirectory)
End Function

Exception is: InvalidOperationException - The current type, is an interface and cannot be constructed. Are you missing a type mapping?

In my case, I was getting this error despite registering an existing instance for the interface in question.

Turned out, it was because I was using Unity in WebForms by way of the Unity.WebForms Nuget package, and I had specified a Hierarchical Lifetime manager for the dependency I was providing an instance for, yet a Transient lifetime manager for a subsequent type that depended on the previous type - not usually an issue - but with Unity.WebForms, the lifetime managers work a little differently... your injected types seem to require a Hierarchical lifetime manager, but a new container is still created for every web request (because of the architecture of web forms I guess) as explained excellently in this post.

Anyway, I resolved it by simply not specifying a lifetime manager for the types/instances when registering them.

i.e.

container.RegisterInstance<IMapper>(MappingConfig.GetMapper(), new HierarchicalLifetimeManager());    
container.RegisterType<IUserContext, UserContext>(new TransientLifetimeManager());

becomes

container.RegisterInstance<IMapper>(MappingConfig.GetMapper());
container.RegisterType<IUserContext, UserContext>();

So that IMapper can be resolved successfully here:

public class UserContext : BaseContext, IUserContext
{
    public UserContext(IMapper _mapper) : base(_mapper)
    {

    }
    ...
}

Warning: X may be used uninitialized in this function

You get the warning because you did not assign a value to one, which is a pointer. This is undefined behavior.

You should declare it like this:

Vector* one = malloc(sizeof(Vector));

or like this:

Vector one;

in which case you need to replace -> operator with . like this:

one.a = 12;
one.b = 13;
one.c = -11;

Finally, in C99 and later you can use designated initializers:

Vector one = {
   .a = 12
,  .b = 13
,  .c = -11
};

How to center text vertically with a large font-awesome icon?

This worked well for me.

i.fa {
  line-height: 100%;
}

What is the difference between Left, Right, Outer and Inner Joins?

Inner join: Only show rows, when has it data from both of the tables.

Outer join: (left/right): Show the all result from the left / right table with the paired row(s), if it exists or not.

data.frame rows to a list

Like @flodel wrote: This converts your dataframe into a list that has the same number of elements as number of rows in dataframe:

NewList <- split(df, f = seq(nrow(df)))

You can additionaly add a function to select only those columns that are not NA in each element of the list:

NewList2 <- lapply(NewList, function(x) x[,!is.na(x)])

JNI converting jstring to char *

Here's a a couple of useful link that I found when I started with JNI

http://en.wikipedia.org/wiki/Java_Native_Interface
http://download.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html

concerning your problem you can use this

JNIEXPORT void JNICALL Java_ClassName_MethodName(JNIEnv *env, jobject obj, jstring javaString)   
{
   const char *nativeString = env->GetStringUTFChars(javaString, 0);

   // use your string

   env->ReleaseStringUTFChars(javaString, nativeString);
}

Android webview slow

I think the following works best:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
    webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}

Android 19 has Chromium engine for WebView. I guess it works better with hardware acceleration.

Laravel Checking If a Record Exists

$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
   // user doesn't exist
}

can be written as

if (User::where('email', '=', Input::get('email'))->first() === null) {
   // user doesn't exist
}

This will return true or false without assigning a temporary variable if that is all you are using $user for in the original statement.

Several ports (8005, 8080, 8009) required by Tomcat Server at localhost are already in use

If you are in Java EE prospective in Eclipse and trying to start the Tomcat Server in Eclipse in debug mode, then you will get such errors. You must switch to debug prospective in Eclipse. I have solved my problem like this.

Escape sequence \f - form feed - what exactly is it?

From wiki page

12 (form feed, \f, ^L), to cause a printer to eject paper to the top of the next page, or a video terminal to clear the screen.

or more details here.

It seems that this symbol is rather obsolete now and the way it is processed may be(?) implementation dependent. At least for me your code gives the following output (xcode gcc 4.2, gdb console):

hello
    goodbye

OR condition in Regex

A classic "or" would be |. For example, ab|de would match either side of the expression.

However, for something like your case you might want to use the ? quantifier, which will match the previous expression exactly 0 or 1 times (1 times preferred; i.e. it's a "greedy" match). Another (probably more relyable) alternative would be using a custom character group:

\d+\s+[A-Z\s]+\s+[A-Z][A-Za-z]+

This pattern will match:

  • \d+: One or more numbers.
  • \s+: One or more whitespaces.
  • [A-Z\s]+: One or more uppercase characters or space characters
  • \s+: One or more whitespaces.
  • [A-Z][A-Za-z\s]+: An uppercase character followed by at least one more character (uppercase or lowercase) or whitespaces.

If you'd like a more static check, e.g. indeed only match ABC and A ABC, then you can combine a (non-matching) group and define the alternatives inside (to limit the scope):

\d (?:ABC|A ABC) Street

Or another alternative using a quantifier:

\d (?:A )?ABC Street

Onclick on bootstrap button

Seem no solutions fix the problem:

$(".anima-area").on('click', function (e) {
            return false; //return true;
});
$(".anima-area").on('click', function (e) {
            e.preventDefault();
});
 $(".anima-area").click(function (r) {
           e.preventDefault();
});
$(".anima-area").click(function () {
           return false; //return true;
});

Bootstrap button always maintain th pressed status and block all .click code. If i remove .click function button comeback to work good.

Java Timer vs ExecutorService?

Here's some more good practices around Timer use:

http://tech.puredanger.com/2008/09/22/timer-rules/

In general, I'd use Timer for quick and dirty stuff and Executor for more robust usage.