Programs & Examples On #Rsls

Runtime Shared Library, used in Adobe Flash Platform applications.

C# Checking if button was clicked

i am very new to this website. I am an undergraduate student, doing my Bachelor Of Computer Application. I am doing a simple program in Visual Studio using C# and I came across the same problem, how to check whether a button is clicked? I wanted to do this,

if(-button1 is clicked-) then
{
this should happen;
}
if(-button2 is clicked-) then
{
this should happen;
}

I didn't know what to do, so I tried searching for the solution in the internet. I got many solutions which didn't help me. So, I tried something on my own and did this,

int i;
private void button1_Click(object sender, EventArgs e)
        {
            i = 1;
            label3.Text = "Principle";
            label4.Text = "Rate";
            label5.Text = "Time";
            label6.Text = "Simple Interest";
        }


private void button2_Click(object sender, EventArgs e)
        {
            i = 2;
            label3.Text = "SI";
            label4.Text = "Rate";
            label5.Text = "Time";
            label6.Text = "Principle";
        }
private void button5_Click(object sender, EventArgs e)
        {

            try
            {
                if (i == 1)
                {
                    si = (Convert.ToInt32(textBox1.Text) * Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text)) / 100;
                    textBox4.Text = Convert.ToString(si);
                }
                if (i == 2)
                {
                    p = (Convert.ToInt32(textBox1.Text) * 100) / (Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text));
                    textBox4.Text = Convert.ToString(p);
                }

I declared a variable "i" and assigned it with different values in different buttons and checked the value of i in the if function. It worked. Give your suggestions if any. Thank you.

How to merge a list of lists with same type of items to a single list of items?

Here's the C# integrated syntax version:

var items =
    from list in listOfList
    from item in list
    select item;

Why is my JQuery selector returning a n.fn.init[0], and what is it?

Another approach(Inside of $function to asure that the each is executed on document ready):

var ids = [1,2];
$(function(){
  $('.checkbox-wrapper>input[type="checkbox"]').each(function(i,item){
    if(ids.indexOf($(item).data('id')) > -1){
       $(item).prop("checked", "checked");
    }
  });
});

Working fiddle: https://jsfiddle.net/robertrozas/w5uda72v/

What is the n.fn.init[0], and why it is returned? Why are my two seemingly identical JQuery functions returning different things?

Answer: It seems that your elements are not in the DOM yet, when you are trying to find them. As @Rory McCrossan pointed out, the length:0 means that it doesn't find any element based on your search criteria.

About n.fn.init[0], lets look at the core of the Jquery Library:

var jQuery = function( selector, context ) {
   return new jQuery.fn.init( selector, context );
};

Looks familiar, right?, now in a minified version of jquery, this should looks like:

var n = function( selector, context ) {
   return new n.fn.init( selector, context );
};

So when you use a selector you are creating an instance of the jquery function; when found an element based on the selector criteria it returns the matched elements; when the criteria does not match anything it returns the prototype object of the function.

What is the difference between const and readonly in C#?

There is notable difference between const and readonly fields in C#.Net

const is by default static and needs to be initialized with constant value, which can not be modified later on. Change of value is not allowed in constructors, too. It can not be used with all datatypes. For ex- DateTime. It can not be used with DateTime datatype.

public const DateTime dt = DateTime.Today;  //throws compilation error
public const string Name = string.Empty;    //throws compilation error
public readonly string Name = string.Empty; //No error, legal

readonly can be declared as static, but not necessary. No need to initialize at the time of declaration. Its value can be assigned or changed using constructor. So, it gives advantage when used as instance class member. Two different instantiation may have different value of readonly field. For ex -

class A
{
    public readonly int Id;

    public A(int i)
    {
        Id = i;
    }
}

Then readonly field can be initialised with instant specific values, as follows:

A objOne = new A(5);
A objTwo = new A(10);

Here, instance objOne will have value of readonly field as 5 and objTwo has 10. Which is not possible using const.

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

First you have to go config.inc.php file then change the following instruction

$cfg['Servers'][$i]['user'] ='';
$cfg['Servers'][$i]['password'] =''; 

or

enter image description here

++i or i++ in for loops ??

For integers, there is no difference between pre- and post-increment.

If i is an object of a non-trivial class, then ++i is generally preferred, because the object is modified and then evaluated, whereas i++ modifies after evaluation, so requires a copy to be made.

The model item passed into the dictionary is of type .. but this dictionary requires a model item of type

The error means that you're navigating to a view whose model is declared as typeof Foo (by using @model Foo), but you actually passed it a model which is typeof Bar (note the term dictionary is used because a model is passed to the view via a ViewDataDictionary).

The error can be caused by

Passing the wrong model from a controller method to a view (or partial view)

Common examples include using a query that creates an anonymous object (or collection of anonymous objects) and passing it to the view

var model = db.Foos.Select(x => new
{
    ID = x.ID,
    Name = x.Name
};
return View(model); // passes an anonymous object to a view declared with @model Foo

or passing a collection of objects to a view that expect a single object

var model = db.Foos.Where(x => x.ID == id);
return View(model); // passes IEnumerable<Foo> to a view declared with @model Foo

The error can be easily identified at compile time by explicitly declaring the model type in the controller to match the model in the view rather than using var.

Passing the wrong model from a view to a partial view

Given the following model

public class Foo
{
    public Bar MyBar { get; set; }
}

and a main view declared with @model Foo and a partial view declared with @model Bar, then

Foo model = db.Foos.Where(x => x.ID == id).Include(x => x.Bar).FirstOrDefault();
return View(model);

will return the correct model to the main view. However the exception will be thrown if the view includes

@Html.Partial("_Bar") // or @{ Html.RenderPartial("_Bar"); }

By default, the model passed to the partial view is the model declared in the main view and you need to use

@Html.Partial("_Bar", Model.MyBar) // or @{ Html.RenderPartial("_Bar", Model.MyBar); }

to pass the instance of Bar to the partial view. Note also that if the value of MyBar is null (has not been initialized), then by default Foo will be passed to the partial, in which case, it needs to be

@Html.Partial("_Bar", new Bar())

Declaring a model in a layout

If a layout file includes a model declaration, then all views that use that layout must declare the same model, or a model that derives from that model.

If you want to include the html for a separate model in a Layout, then in the Layout, use @Html.Action(...) to call a [ChildActionOnly] method initializes that model and returns a partial view for it.

Set specific precision of a BigDecimal

The title of the question asks about precision. BigDecimal distinguishes between scale and precision. Scale is the number of decimal places. You can think of precision as the number of significant figures, also known as significant digits.

Some examples in Clojure.

(.scale     0.00123M) ; 5
(.precision 0.00123M) ; 3

(In Clojure, The M designates a BigDecimal literal. You can translate the Clojure to Java if you like, but I find it to be more compact than Java!)

You can easily increase the scale:

(.setScale 0.00123M 7) ; 0.0012300M

But you can't decrease the scale in the exact same way:

(.setScale 0.00123M 3) ; ArithmeticException Rounding necessary

You'll need to pass a rounding mode too:

(.setScale 0.00123M 3 BigDecimal/ROUND_HALF_EVEN) ;
; Note: BigDecimal would prefer that you use the MathContext rounding
; constants, but I don't have them at my fingertips right now.

So, it is easy to change the scale. But what about precision? This is not as easy as you might hope!

It is easy to decrease the precision:

(.round 3.14159M (java.math.MathContext. 3)) ; 3.14M

But it is not obvious how to increase the precision:

(.round 3.14159M (java.math.MathContext. 7)) ; 3.14159M (unexpected)

For the skeptical, this is not just a matter of trailing zeros not being displayed:

(.precision (.round 3.14159M (java.math.MathContext. 7))) ; 6 
; (same as above, still unexpected)

FWIW, Clojure is careful with trailing zeros and will show them:

4.0000M ; 4.0000M
(.precision 4.0000M) ; 5

Back on track... You can try using a BigDecimal constructor, but it does not set the precision any higher than the number of digits you specify:

(BigDecimal. "3" (java.math.MathContext. 5)) ; 3M
(BigDecimal. "3.1" (java.math.MathContext. 5)) ; 3.1M

So, there is no quick way to change the precision. I've spent time fighting this while writing up this question and with a project I'm working on. I consider this, at best, A CRAZYTOWN API, and at worst a bug. People. Seriously?

So, best I can tell, if you want to change precision, you'll need to do these steps:

  1. Lookup the current precision.
  2. Lookup the current scale.
  3. Calculate the scale change.
  4. Set the new scale

These steps, as Clojure code:

(def x 0.000691M) ; the input number
(def p' 1) ; desired precision
(def s' (+ (.scale x) p' (- (.precision x)))) ; desired new scale
(.setScale x s' BigDecimal/ROUND_HALF_EVEN)
; 0.0007M

I know, this is a lot of steps just to change the precision!

Why doesn't BigDecimal already provide this? Did I overlook something?

Python: Assign print output to a variable

Please note, I wrote this answer based on Python 3.x. No worries you can assign print() statement to the variable like this.

>>> var = print('some text')
some text
>>> var
>>> type(var)
<class 'NoneType'>

According to the documentation,

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

That's why we cannot assign print() statement values to the variable. In this question you have ask (or any function). So print() also a function with the return value with None. So the return value of python function is None. But you can call the function(with parenthesis ()) and save the return value in this way.

>>> var = some_function()

So the var variable has the return value of some_function() or the default value None. According to the documentation about print(), All non-keyword arguments are converted to strings like str() does and written to the stream. Lets look what happen inside the str().

Return a string version of object. If object is not provided, returns the empty string. Otherwise, the behavior of str() depends on whether encoding or errors is given, as follows.

So we get a string object, then you can modify the below code line as follows,

>>> var = str(some_function())

or you can use str.join() if you really have a string object.

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

change can be as follows,

>>> var = ''.join(some_function())  # you can use this if some_function() really returns a string value

Why does the 260 character path length limit exist in Windows?

Quoting this article https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#maximum-path-length-limitation

Maximum Path Length Limitation

In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string<NUL>" where "<NUL>" represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)

Now we see that it is 1+2+256+1 or [drive][:\][path][null] = 260. One could assume that 256 is a reasonable fixed string length from the DOS days. And going back to the DOS APIs we realize that the system tracked the current path per drive, and we have 26 (32 with symbols) maximum drives (and current directories).

The INT 0x21 AH=0x47 says “This function returns the path description without the drive letter and the initial backslash.” So we see that the system stores the CWD as a pair (drive, path) and you ask for the path by specifying the drive (1=A, 2=B, …), if you specify a 0 then it assumes the path for the drive returned by INT 0x21 AH=0x15 AL=0x19. So now we know why it is 260 and not 256, because those 4 bytes are not stored in the path string.

Why a 256 byte path string, because 640K is enough RAM.

How to execute Ant build in command line

is it still actual?

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

How do I convert a date/time to epoch time (unix time/seconds since 1970) in Perl?

$ENV{TZ}="GMT";
POSIX::tzset();
$time = POSIX::mktime($s,$m,$h,$d,$mo-1,$y-1900);

Download file from web in Python 3

I use requests package whenever I want something related to HTTP requests because its API is very easy to start with:

first, install requests

$ pip install requests

then the code:

from requests import get  # to make GET request


def download(url, file_name):
    # open in binary mode
    with open(file_name, "wb") as file:
        # get request
        response = get(url)
        # write to file
        file.write(response.content)

what is the difference between XSD and WSDL

If someone is looking for analogy , this answer might be helpful.

WSDL is like 'SHOW TABLE STATUS' command in mysql. It defines all the elements(request type, response type, format of URL to hit request,etc.,) which should be part of XML. By definition I mean: 1) Names of request or response 2) What should be treated as input , what should be treated as output.

XSD is like DESCRIBE command in mysql. It tells what all variables and their types, a request and response contains.

Adding and removing style attribute from div with jquery

In case of .css method in jQuery for !important rule will not apply.

In this case we should use .attr function.

For Example: If you want to add style as below:

<div id='voltaic_holder' style='position:absolute;top:-75px !important'>

You should use:

$("#voltaic_holder").attr("style", "position:absolute;top:-75px !important");

Hope it helps some one.

Check if textbox has empty value

if ( $("#txt").val().length > 0 )
{
  // do something
}

Your method fails when there is more than 1 space character inside the textbox.

Uncaught TypeError: Cannot read property 'msie' of undefined

$.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

How can I write output from a unit test?

Solved with the following example:

public void CheckConsoleOutput()
{
    Console.WriteLine("Hello, World!");
    Trace.WriteLine("Trace Trace the World");
    Debug.WriteLine("Debug Debug World");
    Assert.IsTrue(true);
}

After running this test, under 'Test Passed', there is the option to view the output, which will bring up the output window.

Add Marker function with Google Maps API

You have added the add marker method call outside the function and that causes it to execute before the initialize method which will be called when google maps script loads and thus the marker is not added because map is not initialized Do as below.... Create separate method TestMarker and call it from initialize.

<script type="text/javascript">

    // Standard google maps function
    function initialize() {
        var myLatlng = new google.maps.LatLng(40.779502, -73.967857);
        var myOptions = {
            zoom: 12,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        TestMarker();
    }

    // Function for adding a marker to the page.
    function addMarker(location) {
        marker = new google.maps.Marker({
            position: location,
            map: map
        });
    }

    // Testing the addMarker function
    function TestMarker() {
           CentralPark = new google.maps.LatLng(37.7699298, -122.4469157);
           addMarker(CentralPark);
    }
</script>

Notification bar icon turns white in Android 5 Lollipop

Notifications are greyscale as explained below. They are not black-and-white, despite what others have written. You have probably seen icons with multiple shades, like network strength bars.

Prior to API 21 (Lollipop 5.0), colour icons work. You could force your application to target API 20, but that limits the features available to your application, so it is not recommended. You could test the running API level and set either a colour icon or a greyscale icon appropriately, but this is likely not worthwhile. In most cases, it is best to go with a greyscale icon.

Images have four channels, RGBA (red / green / blue / alpha). For notification icons, Android ignores the R, G, and B channels. The only channel that counts is Alpha, also known as opacity. Design your icon with an editor that gives you control over the Alpha value of your drawing colours.

How Alpha values generate a greyscale image:

  • Alpha = 0 (transparent) — These pixels are transparent, showing the background colour.
  • Alpha = 255 (opaque) — These pixels are white.
  • Alpha = 1 ... 254 — These pixels are exactly what you would expect, providing the shades between transparent and white.

Changing it up with setColor:

  • Call NotificationCompat.Builder.setColor(int argb). From the documentation for Notification.color:

    Accent color (an ARGB integer like the constants in Color) to be applied by the standard Style templates when presenting this notification. The current template design constructs a colorful header image by overlaying the icon image (stenciled in white) atop a field of this color. Alpha components are ignored.

    My testing with setColor shows that Alpha components are not ignored; instead, they still provide greyscale. Higher Alpha values turn a pixel white. Lower Alpha values turn a pixel to the background colour (black on my device) in the notification area, or to the specified colour in the pull-down notification. (It seems others have reported slightly different behavior, so be aware!)

Java best way for string find and replace?

you can use pattern matcher as well, which will replace all in one shot.

Pattern keyPattern = Pattern.compile(key); Matcher matcher = keyPattern.matcher(str); String nerSrting = matcher.replaceAll(value);

Nginx - Customizing 404 page

These answers are no longer recommended since try_files works faster than if in this context. Simply add try_files in your php location block to test if the file exists, otherwise return a 404.

location ~ \.php {
    try_files $uri =404;
    ...
}

Make anchor link go some pixels above where it's linked to

The easiest solution:

CSS

#link {
    top:-120px; /* -(some pixels above) */
    position:relative;
    z-index:5;
}

HTML

<body>
    <a href="#link">Link</a>
    <div>
        <div id="link"></div> /*this div should placed inside a target div in the page*/
        text
        text
        text
    <div>
</body>

Python socket receive - incoming packets always have a different size

I know this is old, but I hope this helps someone.

Using regular python sockets I found that you can send and receive information in packets using sendto and recvfrom

# tcp_echo_server.py
import socket

ADDRESS = ''
PORT = 54321

connections = []
host = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host.setblocking(0)
host.bind((ADDRESS, PORT))
host.listen(10)  # 10 is how many clients it accepts

def close_socket(connection):
    try:
        connection.shutdown(socket.SHUT_RDWR)
    except:
        pass
    try:
        connection.close()
    except:
        pass

def read():
    for i in reversed(range(len(connections))):
        try:
            data, sender = connections[i][0].recvfrom(1500)
            return data
        except (BlockingIOError, socket.timeout, OSError):
            pass
        except (ConnectionResetError, ConnectionAbortedError):
            close_socket(connections[i][0])
            connections.pop(i)
    return b''  # return empty if no data found

def write(data):
    for i in reversed(range(len(connections))):
        try:
            connections[i][0].sendto(data, connections[i][1])
        except (BlockingIOError, socket.timeout, OSError):
            pass
        except (ConnectionResetError, ConnectionAbortedError):
            close_socket(connections[i][0])
            connections.pop(i)

# Run the main loop
while True:
    try:
        con, addr = host.accept()
        connections.append((con, addr))
    except BlockingIOError:
        pass

    data = read()
    if data != b'':
        print(data)
        write(b'ECHO: ' + data)
        if data == b"exit":
            break

# Close the sockets
for i in reversed(range(len(connections))):
    close_socket(connections[i][0])
    connections.pop(i)
close_socket(host)

The client is similar

# tcp_client.py
import socket

ADDRESS = "localhost"
PORT = 54321

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ADDRESS, PORT))
s.setblocking(0)

def close_socket(connection):
    try:
        connection.shutdown(socket.SHUT_RDWR)
    except:
        pass
    try:
        connection.close()
    except:
        pass

def read():
    """Read data and return the read bytes."""
    try:
        data, sender = s.recvfrom(1500)
        return data
    except (BlockingIOError, socket.timeout, AttributeError, OSError):
        return b''
    except (ConnectionResetError, ConnectionAbortedError, AttributeError):
        close_socket(s)
        return b''

def write(data):
    try:
        s.sendto(data, (ADDRESS, PORT))
    except (ConnectionResetError, ConnectionAbortedError):
        close_socket(s)

while True:
    msg = input("Enter a message: ")
    write(msg.encode('utf-8'))

    data = read()
    if data != b"":
        print("Message Received:", data)

    if msg == "exit":
        break

close_socket(s)

When to encode space to plus (+) or %20?

So, the answers here are all a bit incomplete. The use of a '%20' to encode a space in URLs is explicitly defined in RFC3986, which defines how a URI is built. There is no mention in this specification of using a '+' for encoding spaces - if you go solely by this specification, a space must be encoded as '%20'.

The mention of using '+' for encoding spaces comes from the various incarnations of the HTML specification - specifically in the section describing content type 'application/x-www-form-urlencoded'. This is used for posting form data.

Now, the HTML 2.0 Specification (RFC1866) explicitly said, in section 8.2.2, that the Query part of a GET request's URL string should be encoded as 'application/x-www-form-urlencoded'. This, in theory, suggests that it's legal to use a '+' in the URL in the query string (after the '?').

But... does it really? Remember, HTML is itself a content specification, and URLs with query strings can be used with content other than HTML. Further, while the later versions of the HTML spec continue to define '+' as legal in 'application/x-www-form-urlencoded' content, they completely omit the part saying that GET request query strings are defined as that type. There is, in fact, no mention whatsoever about the query string encoding in anything after the HTML 2.0 spec.

Which leaves us with the question - is it valid? Certainly there's a LOT of legacy code which supports '+' in query strings, and a lot of code which generates it as well. So odds are good you won't break if you use '+'. (And, in fact, I did all the research on this recently because I discovered a major site which failed to accept '%20' in a GET query as a space. They actually failed to decode ANY percent encoded character. So the service you're using may be relevant as well.)

But from a pure reading of the specifications, without the language from the HTML 2.0 specification carried over into later versions, URLs are covered entirely by RFC3986, which means spaces ought to be converted to '%20'. And definitely that should be the case if you are requesting anything other than an HTML document.

make html text input field grow as I type?

I know this is a seriously old post - but my answer might be useful to others anyway, so here goes. I found that if my CSS style definition for the contenteditable div has a min-height of 200 instead of a height of 200 , then the div scales automatically.

How to get the current date and time of your timezone in Java?

DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("PST"));
final String dateTimeString = df.format(new Date());

How do I set up HttpContent for my HttpClient PostAsync second parameter?

    public async Task<ActionResult> Index()
    {
        apiTable table = new apiTable();
        table.Name = "Asma Nadeem";
        table.Roll = "6655";

        string str = "";
        string str2 = "";

        HttpClient client = new HttpClient();

        string json = JsonConvert.SerializeObject(table);

        StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

        var response = await client.PostAsync("http://YourSite.com/api/apiTables", httpContent);

        str = "" + response.Content + " : " + response.StatusCode;

        if (response.IsSuccessStatusCode)
        {       
            str2 = "Data Posted";
        }

        return View();
    }

html select option separator

The disabled option approach seems to look the best and be the best supported. I've also included an example of using the optgroup.

optgroup (this way kinda sucks):

_x000D_
_x000D_
<select>_x000D_
    <optgroup>_x000D_
        <option>First</option>_x000D_
    </optgroup>_x000D_
    <optgroup label="_________">_x000D_
        <option>Second</option>_x000D_
        <option>Third</option>_x000D_
    </optgroup>_x000D_
</select>
_x000D_
_x000D_
_x000D_

disabled option (a bit better):

_x000D_
_x000D_
<select>_x000D_
    <option>First</option>_x000D_
    <option disabled>_________</option>_x000D_
    <option>Second</option>_x000D_
    <option>Third</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

And if you want to be really fancy, use the horizontal unicode box drawing character.
(BEST OPTION!)

_x000D_
_x000D_
<select>_x000D_
    <option>First</option>_x000D_
    <option disabled>----------</option>_x000D_
    <option>Second</option>_x000D_
    <option>Third</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/JFDgH/2/

How do you UDP multicast in Python?

In order to Join multicast group Python uses native OS socket interface. Due to portability and stability of Python environment many of socket options are directly forwarded to native socket setsockopt call. Multicast mode of operation such as joining and dropping group membership can be accomplished by setsockopt only.

Basic program for receiving multicast IP packet can look like:

from socket import *

multicast_port  = 55555
multicast_group = "224.1.1.1"
interface_ip    = "10.11.1.43"

s = socket(AF_INET, SOCK_DGRAM )
s.bind(("", multicast_port ))
mreq = inet_aton(multicast_group) + inet_aton(interface_ip)
s.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, str(mreq))

while 1:
    print s.recv(1500)

Firstly it creates socket, binds it and triggers triggers multicast group joining by issuing setsockopt. At very end it receives packets forever.

Sending multicast IP frames is straight forward. If you have single NIC in your system sending such packets does not differ from usual UDP frames sending. All you need to take care of is just set correct destination IP address in sendto() method.

I noticed that lot of examples around Internet works by accident in fact. Even on official python documentation. Issue for all of them are using struct.pack incorrectly. Please be advised that typical example uses 4sl as format and it is not aligned with actual OS socket interface structure.

I will try to describe what happens underneath the hood when exercising setsockopt call for python socket object.

Python forwards setsockopt method call to native C socket interface. Linux socket documentation (see man 7 ip) introduces two forms of ip_mreqn structure for IP_ADD_MEMBERSHIP option. Shortest is form is 8 bytes long and longer is 12 bytes long. Above example generates 8 byte setsockopt call where first four bytes define multicast_group and second four bytes define interface_ip.

Viewing my IIS hosted site on other machines on my network

Very Late Answer but I will highlight some point as I had to deal with it years ago setting up my IIS site across network

  1. Both your machines should be connected to the same network (same wireless network is fine)
  2. Access your remote machine via IP 168.192.x.x or via http://his-pc-name (do not forget the http part)
  3. This will server the default IIS page on the remote machine (same that is served through localhost). If you want to server another site, [you have to make that default] first1.

Make sure your IIS is working fine on remote machine by checking localhost which should served the default site. Also make sure your firewall is configured to allow connection via port 80 or you can just disable firewall for the time being for testing purposes.

How do you get the current page number of a ViewPager for Android?

in the latest packages you can also use

vp.getCurrentItem()

or

vp is the viewPager ,

pageListener = new PageListener();
vp.setOnPageChangeListener(pageListener);

you have to put a page change listener for your viewPager. There is no method on viewPager to get the current page.

private int currentPage;

    private static class PageListener extends SimpleOnPageChangeListener{
            public void onPageSelected(int position) {
                Log.i(TAG, "page selected " + position);
                   currentPage = position;
        }
    }

Make new column in Panda dataframe by adding values from other columns

You could use sum function to achieve that as @EdChum mentioned in the comment:

df['C'] =  df[['A', 'B']].sum(axis=1)

In [245]: df
Out[245]: 
   A  B   C
0  1  4   5
1  2  6   8
2  3  9  12

Move textfield when keyboard appears swift

The best way is using NotificationCenter to catch keyboard actions. You can follow the steps in this short article https://medium.com/@demirciy/keyboard-handling-deb1a96a8207

convert month from name to number

Use

date("F", mktime(0, 0, 0, ($month)));

where, $month value will be 1 -> 12

jquery change class name

I think he wants to replace a class name.

Something like this would work:

$(document).ready(function(){
    $('.blue').removeClass('blue').addClass('green');
});

from http://monstertut.com/2012/06/use-jquery-to-change-css-class/

How to select a single child element using jQuery?

<html>
<title>

    </title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">
<body>




<!-- <asp:LinkButton ID="MoreInfoButton" runat="server" Text="<%#MoreInfo%>" > -->
 <!-- </asp:LinkButton> -->
<!-- </asp:LinkButton> -->

<br />
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>




</asp:Repeater>


</body>
<!-- Predefined JavaScript -->
<script src="jquery.js"></script>
<script src="bootstrap.js"></script>

<script>

 $(function () {
        $('a').click(function() {
            $(this).parent().children('.dataContentSectionMessages').slideToggle();
        });
    });

    </script>


</html>

Call PHP function from Twig template

There is already a Twig extension that lets you call PHP functions form your Twig templates like:

Hi, I am unique: {{ uniqid() }}.

And {{ floor(7.7) }} is floor of 7.7.

See official extension repository.

Run cmd commands through Java

one of the way to execute cmd from java !

public void executeCmd() {
    String anyCommand="your command";
    try {
        Process process = Runtime.getRuntime().exec("cmd /c start cmd.exe /K " + anyCommand);

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

Getting all file names from a folder using C#

I would recommend you google 'Read objects in folder'. You might need to create a reader and a list and let the reader read all the object names in the folder and add them to the list in n loops.

jQuery table sort

I love this accepted answer, however, rarely do you get requirements to sort html and not have to add icons indicating the sorting direction. I took the accept answer's usage example and fixed that quickly by simply adding bootstrap to my project, and adding the following code:

<div></div>

inside each <th> so that you have a place to set the icon.

setIcon(this, inverse);

from the accepted answer's Usage, below the line:

th.click(function () {

and by adding the setIcon method:

function setIcon(element, inverse) {

        var iconSpan = $(element).find('div');

        if (inverse == false) {
            $(iconSpan).removeClass();
            $(iconSpan).addClass('icon-white icon-arrow-up');
        } else {
            $(iconSpan).removeClass();
            $(iconSpan).addClass('icon-white icon-arrow-down');
        }
        $(element).siblings().find('div').removeClass();
    }

Here is a demo. --You need to either run the demo in Firefox or IE, or disable Chrome's MIME-type checking for the demo to work. It depends on the sortElements Plugin, linked by the accepted answer, as an external resource. Just a heads up!

converting multiple columns from character to numeric format in r

You could use convert from the hablar package:

library(dplyr)
library(hablar)

# Sample df (stolen from the solution by Luca Braglia)
df <- tibble("a" = as.character(0:5),
                 "b" = paste(0:5, ".1", sep = ""),
                 "c" = letters[1:6])

# insert variable names in num()
df %>% convert(num(a, b))

Which gives you:

# A tibble: 6 x 3
      a     b c    
  <dbl> <dbl> <chr>
1    0. 0.100 a    
2    1. 1.10  b    
3    2. 2.10  c    
4    3. 3.10  d    
5    4. 4.10  e    
6    5. 5.10  f   

Or if you are lazy, let retype() from hablar guess the right data type:

df %>% retype()

which gives you:

# A tibble: 6 x 3
      a     b c    
  <int> <dbl> <chr>
1     0 0.100 a    
2     1 1.10  b    
3     2 2.10  c    
4     3 3.10  d    
5     4 4.10  e    
6     5 5.10  f   

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For the Collatz problem, you can get a significant boost in performance by caching the "tails". This is a time/memory trade-off. See: memoization (https://en.wikipedia.org/wiki/Memoization). You could also look into dynamic programming solutions for other time/memory trade-offs.

Example python implementation:

import sys

inner_loop = 0

def collatz_sequence(N, cache):
    global inner_loop

    l = [ ]
    stop = False
    n = N

    tails = [ ]

    while not stop:
        inner_loop += 1
        tmp = n
        l.append(n)
        if n <= 1:
            stop = True  
        elif n in cache:
            stop = True
        elif n % 2:
            n = 3*n + 1
        else:
            n = n // 2
        tails.append((tmp, len(l)))

    for key, offset in tails:
        if not key in cache:
            cache[key] = l[offset:]

    return l

def gen_sequence(l, cache):
    for elem in l:
        yield elem
        if elem in cache:
            yield from gen_sequence(cache[elem], cache)
            raise StopIteration

if __name__ == "__main__":
    le_cache = {}

    for n in range(1, 4711, 5):
        l = collatz_sequence(n, le_cache)
        print("{}: {}".format(n, len(list(gen_sequence(l, le_cache)))))

    print("inner_loop = {}".format(inner_loop))

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

If you want the structure to have a certain size with GCC for example use __attribute__((packed)).

On Windows you can set the alignment to one byte when using the cl.exe compier with the /Zp option.

Usually it is easier for the CPU to access data that is a multiple of 4 (or 8), depending platform and also on the compiler.

So it is a matter of alignment basically.

You need to have good reasons to change it.

Error "The input device is not a TTY"

It's not exactly what you are asking, but:

The -T key would help people who are using docker-compose exec!

docker-compose -f /srv/backend_bigdata/local.yml exec -T postgres backup

find vs find_by vs where

The best part of working with any open source technology is that you can inspect length and breadth of it. Checkout this link

find_by ~> Finds the first record matching the specified conditions. There is no implied ordering so if order matters, you should specify it yourself. If no record is found, returns nil.

find ~> Finds the first record matching the specified conditions , but if no record is found, it raises an exception but that is done deliberately.

Do checkout the above link, it has all the explanation and use cases for the following two functions.

fatal: could not read Username for 'https://github.com': No such file or directory

Note that if you are getting this error instead:

fatal: could not read Username for 'https://github.com': No error

Then you need to update your Git to version 2.16 or later.

How to use range-based for() loop with std::map?

In C++17 this is called structured bindings, which allows for the following:

std::map< foo, bar > testing = { /*...blah...*/ };
for ( const auto& [ k, v ] : testing )
{
  std::cout << k << "=" << v << "\n";
}

Spark Kill Running Application

This might not be an ethical and preferred solution but it helps in environments where you can't access the console to kill the job using yarn application command.

Steps are

Go to application master page of spark job. Click on the jobs section. Click on the active job's active stage. You will see "kill" button right next to the active stage.

This works if the succeeding stages are dependent on the currently running stage. Though it marks job as " Killed By User"

The current .NET SDK does not support targeting .NET Standard 2.0 error in Visual Studio 2017 update 15.3

Actually, to me it happened in opposite way to another answers.

I did install the latest .NET Core SDK before the issue appeared (3.0.0-preview2 in my case) having not the latest version of Visual Studio (not sure if that would make any difference).

So, the solution was just to uninstall that latest .NET Core SDK. (This is not perfect if you need it, so you might consider Visual Studio upgrade to the latest one, but at least that solved ongoing issue).

Convert number of minutes into hours & minutes using PHP

Just in case you want to something like:

echo date('G \h\o\u\r\s i \m\i\n\u\t\e\s', mktime(0, 90)); //will return 1 hours 30 minutes
echo date('G \j\a\m i \m\e\n\i\t', mktime(0, 90)); //will return 1 jam 30 menit

How to hide iOS status bar

From UIKit>UIApplication.h:

// Setting statusBarHidden does nothing if your application is using the default UIViewController-based status bar system.
@property(nonatomic,getter=isStatusBarHidden) BOOL statusBarHidden;
- (void)setStatusBarHidden:(BOOL)hidden withAnimation:(UIStatusBarAnimation)animation NS_AVAILABLE_IOS(3_2);

So should set View controller-based status bar appearance to NO

How do I set the default value for an optional argument in Javascript?

You can also do this with ArgueJS:

function (){
  arguments = __({nodebox: undefined, str: [String: "hai"]})

  // and now on, you can access your arguments by
  //   arguments.nodebox and arguments.str
}

How does strtok() split the string into tokens in C?

you can scan the char array looking for the token if you found it just print new line else print the char.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char *s;
    s = malloc(1024 * sizeof(char));
    scanf("%[^\n]", s);
    s = realloc(s, strlen(s) + 1);
    int len = strlen(s);
    char delim =' ';
    for(int i = 0; i < len; i++) {
        if(s[i] == delim) {
            printf("\n");
        }
        else {
            printf("%c", s[i]);
        }
    }
    free(s);
    return 0;
}

Target Unreachable, identifier resolved to null in JSF 2.2

I want to share my experience with this Exception. My JSF 2.2 application worked fine with WildFly 8.0, but one time, when I started server, i got this "Target Unreacheable" exception. Actually, there was no problem with JSF annotations or tags.

Only thing I had to do was cleaning the project. After this operation, my app is working fine again.

I hope this will help someone!

Cosine Similarity between 2 Number Lists

You can use cosine_similarity function form sklearn.metrics.pairwise docs

In [23]: from sklearn.metrics.pairwise import cosine_similarity

In [24]: cosine_similarity([[1, 0, -1]], [[-1,-1, 0]])
Out[24]: array([[-0.5]])

How to maintain aspect ratio using HTML IMG tag

<img src="Runtime Path to photo"
     style="border: 1px solid #000; max-width:64px; max-height:64px;">

php check if array contains all array values from another array

Look at array_intersect().

$containsSearch = count(array_intersect($search_this, $all)) == count($search_this);

How can I get the image url in a Wordpress theme?

I strongly recommend the following:

<img src="<?php echo get_stylesheet_directory_uri(); ?>/img-folder/your_image.jpg">

It works for almost any file you want to add to your wordpress project, be it image or CSS.

How to alter a column and change the default value?

Accepted Answer works good.

In case of Invalid use of NULL value error, on NULL values, update all null values to default value in that column and then try to do the alter.

UPDATE foobar_data SET col = '{}' WHERE col IS NULL;

ALTER TABLE foobar_data MODIFY COLUMN col VARCHAR(255) NOT NULL DEFAULT '{}';

100% width Twitter Bootstrap 3 template

You're right using div.container-fluid and you also need a div.row child. Then, the content must be placed inside without any grid columns. If you have a look at the docs you can find this text:

  • Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper alignment and padding.
  • Use rows to create horizontal groups of columns.

Not using grid columns it's ok as stated here:

  • Content should be placed within columns, and only columns may be immediate children of rows.

And looking at this example, you can read this text:

Full width, single column: No grid classes are necessary for full-width elements.

Here's a live example showing some elements using the correct layout. This way you don't need any custom CSS or hack.

Retrieving JSON Object Literal from HttpServletRequest

There is another way to do it, using org.apache.commons.io.IOUtils to extract the String from the request

String jsonString = IOUtils.toString(request.getInputStream());

Then you can do whatever you want, convert it to JSON or other object with Gson, etc.

JSONObject json = new JSONObject(jsonString);
MyObject myObject = new Gson().fromJson(jsonString, MyObject.class);

Find the IP address of the client in an SSH session

 who | cut -d"(" -f2 |cut -d")" -f1

Resize a large bitmap file to scaled output file on Android

Taking into account that you want to resize to exact size and want to keep as much quality as needed I think you should try this.

  1. Find out the size of the resized image with call of BitmapFactory.decodeFile and providing the checkSizeOptions.inJustDecodeBounds
  2. Calculate the maximum possible inSampleSize you can use on your device to not exceed the memory. bitmapSizeInBytes = 2*width*height; Generally for your picture inSampleSize=2 would be fine since you will need only 2*1944x1296)=4.8Mb? which should feet in memory
  3. Use BitmapFactory.decodeFile with inSampleSize to load the Bitmap
  4. Scale the bitmap to exact size.

Motivation: multiple-steps scaling could give you higher quality picture, however there is no guarantee that it will work better than using high inSampleSize. Actually, I think that you also can use inSampleSize like 5 (not pow of 2) to have direct scaling in one operation. Or just use 4 and then you can just use that image in UI. if you send it to server - than you can do scaling to exact size on server side which allow you to use advanced scaling techniques.

Notes: if the Bitmap loaded in step-3 is at least 4 times larger (so the 4*targetWidth < width) you probably can use several resizing to achieve better quality. at least that works in generic java, in android you don't have the option to specify the interpolation used for scaling http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html

Google Recaptcha v3 example demo

I thought a fully-functioning reCaptcha v3 example demo in PHP, using a Bootstrap 4 form, might be useful to some.

Reference the shown dependencies, swap in your email address and keys (create your own keys here), and the form is ready to test and use. I made code comments to better clarify the logic and also included commented-out console log and print_r lines to quickly enable viewing the validation token and data generated from Google.

The included jQuery function is optional, though it does create a much better user prompt experience in this demo.


PHP file (mail.php):

Add secret key (2 places) and email address where noted.

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

  # BEGIN Setting reCaptcha v3 validation data
  $url = "https://www.google.com/recaptcha/api/siteverify";
  $data = [
    'secret' => "your-secret-key-here",
    'response' => $_POST['token'],
    'remoteip' => $_SERVER['REMOTE_ADDR']
  ];

  $options = array(
    'http' => array(
      'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
      'method'  => 'POST',
      'content' => http_build_query($data)
    )
    );
  
  # Creates and returns stream context with options supplied in options preset 
  $context  = stream_context_create($options);
  # file_get_contents() is the preferred way to read the contents of a file into a string
  $response = file_get_contents($url, false, $context);
  # Takes a JSON encoded string and converts it into a PHP variable
  $res = json_decode($response, true);
  # END setting reCaptcha v3 validation data
   
    // print_r($response); 
# Post form OR output alert and bypass post if false. NOTE: score conditional is optional
# since the successful score default is set at >= 0.5 by Google. Some developers want to
# be able to control score result conditions, so I included that in this example.

  if ($res['success'] == true && $res['score'] >= 0.5) {
 
    # Recipient email
    $mail_to = "[email protected]";
    
    # Sender form data
    $subject = trim($_POST["subject"]);
    $name = str_replace(array("\r","\n"),array(" "," ") , strip_tags(trim($_POST["name"])));
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $phone = trim($_POST["phone"]);
    $message = trim($_POST["message"]);
    
    if (empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL) OR empty($phone) OR empty($subject) OR empty($message)) {
      # Set a 400 (bad request) response code and exit
      http_response_code(400);
      echo '<p class="alert-warning">Please complete the form and try again.</p>';
      exit;
    }

    # Mail content
    $content = "Name: $name\n";
    $content .= "Email: $email\n\n";
    $content .= "Phone: $phone\n";
    $content .= "Message:\n$message\n";

    # Email headers
    $headers = "From: $name <$email>";

    # Send the email
    $success = mail($mail_to, $subject, $content, $headers);
    
    if ($success) {
      # Set a 200 (okay) response code
      http_response_code(200);
      echo '<p class="alert alert-success">Thank You! Your message has been successfully sent.</p>';
    } else {
      # Set a 500 (internal server error) response code
      http_response_code(500);
      echo '<p class="alert alert-warning">Something went wrong, your message could not be sent.</p>';
    }   

  } else {

    echo '<div class="alert alert-danger">
        Error! The security token has expired or you are a bot.
       </div>';
  }  

} else {
  # Not a POST request, set a 403 (forbidden) response code
  http_response_code(403);
  echo '<p class="alert-warning">There was a problem with your submission, please try again.</p>';
} ?>

HTML <head>

Bootstrap CSS dependency and reCaptcha client-side validation Place between <head> tags - paste your own site-key where noted.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://www.google.com/recaptcha/api.js?render=your-site-key-here"></script>

HTML <body>

Place between <body> tags.

<!-- contact form demo container -->
<section style="margin: 50px 20px;">
  <div style="max-width: 768px; margin: auto;">
    
    <!-- contact form -->
    <div class="card">
      <h2 class="card-header">Contact Form</h2>
      <div class="card-body">
        <form class="contact_form" method="post" action="mail.php">

          <!-- form fields -->
          <div class="row">
            <div class="col-md-6 form-group">
              <input name="name" type="text" class="form-control" placeholder="Name" required>
            </div>
            <div class="col-md-6 form-group">
              <input name="email" type="email" class="form-control" placeholder="Email" required>
            </div>
            <div class="col-md-6 form-group">
              <input name="phone" type="text" class="form-control" placeholder="Phone" required>
            </div>
            <div class="col-md-6 form-group">
              <input name="subject" type="text" class="form-control" placeholder="Subject" required>
            </div>
            <div class="col-12 form-group">
              <textarea name="message" class="form-control" rows="5" placeholder="Message" required></textarea>
            </div>

            <!-- form message prompt -->
            <div class="row">
              <div class="col-12">
                <div class="contact_msg" style="display: none">
                  <p>Your message was sent.</p>
                </div>
              </div>
            </div>

            <div class="col-12">
              <input type="submit" value="Submit Form" class="btn btn-success" name="post">
            </div>

            <!-- hidden reCaptcha token input -->
            <input type="hidden" id="token" name="token">
          </div>

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

  </div>
</section>
<script>
  grecaptcha.ready(function() {
    grecaptcha.execute('your-site-key-here', {action: 'homepage'}).then(function(token) {
       // console.log(token);
       document.getElementById("token").value = token;
    });
    // refresh token every minute to prevent expiration
    setInterval(function(){
      grecaptcha.execute('your-site-key-here', {action: 'homepage'}).then(function(token) {
        console.log( 'refreshed token:', token );
        document.getElementById("token").value = token;
      });
    }, 60000);

  });
</script>

<!-- References for the optional jQuery function to enhance end-user prompts -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="form.js"></script>

Optional jQuery function for enhanced UX (form.js):

(function ($) {
'use strict';

var form = $('.contact_form'),
  message = $('.contact_msg'),
  form_data;

// Success function
function done_func(response) {
  message.fadeIn()
  message.html(response);
  setTimeout(function () {
    message.fadeOut();
  }, 10000);
  form.find('input:not([type="submit"]), textarea').val('');
}

// fail function
function fail_func(data) {
  message.fadeIn()
  message.html(data.responseText);
  setTimeout(function () {
    message.fadeOut();
  }, 10000);
}

form.submit(function (e) {
  e.preventDefault();
  form_data = $(this).serialize();
  $.ajax({
    type: 'POST',
    url: form.attr('action'),
    data: form_data
  })
  .done(done_func)
  .fail(fail_func);
}); })(jQuery);

Twitter Bootstrap hide css class and jQuery

As dfsq said i just had to use removeClass("hide") instead of toggle()

#1071 - Specified key was too long; max key length is 1000 bytes

I was facing same issue, used below query to resolve it.

While creating DB you can use utf-8 encoding

eg. create database my_db character set utf8 collate utf8mb4;

EDIT: (Considering suggestions from comments) Changed utf8_bin to utf8mb4

What is setBounds and how do I use it?

This is a method of the java.awt.Component class. It is used to set the position and size of a component:

setBounds

public void setBounds(int x,
                  int y,
                  int width,
                  int height) 

Moves and resizes this component. The new location of the top-left corner is specified by x and y, and the new size is specified by width and height. Parameters:

  • x - the new x-coordinate of this component
  • y - the new y-coordinate of this component
  • width - the new width of this component
  • height - the new height of this component

x and y as above correspond to the upper left corner in most (all?) cases.

It is a shortcut for setLocation and setSize.

This generally only works if the layout/layout manager are non-existent, i.e. null.

Can I style an image's ALT text with CSS?

You cant style the alt attribute directly in css. However the alt will inherit the styles of the item the alt is on or what is inherited by its parent:

_x000D_
_x000D_
    <div style="background-color:black; height: 50px; width: 50px; color:white;">_x000D_
    <img src="ouch" alt="here i am"/>_x000D_
    <div>
_x000D_
_x000D_
_x000D_

In the above example, the alt text will be black. However with the color:white the alt text is white.

How to make 'submit' button disabled?

Here is a working example (you'll have to trust me that there's a submit() method on the controller - it prints an Object, like {user: 'abc'} if 'abc' is entered in the input field):

<form #loginForm="ngForm" (ngSubmit)="submit(loginForm.value)">
    <input type="text" name="user" ngModel required>
    <button  type="submit"  [disabled]="loginForm.invalid">
        Submit
    </button>
</form>

As you can see:

  • don't use loginForm.form, just use loginForm
  • loginForm.invalid works as well as !loginForm.valid
  • if you want submit() to be passed the correct value(s), the input element should have name and ngModel attributes

Also, this is when you're NOT using the new FormBuilder, which I recommend. Things are very different when using FormBuilder.

Prevent form submission on Enter key press

<form id="form1" runat="server" onkeypress="return event.keyCode != 13;">

Add this Code In Your HTML Page...it will disable ...Enter Button..

TypeError: $(...).modal is not a function with bootstrap Modal

I have resolved this issue in react by using it like this.

window.$('#modal-id').modal();

How to create a zip file in Java

Single file:

String filePath = "/absolute/path/file1.txt";
String zipPath = "/absolute/path/output.zip";

try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipPath))) {
    File fileToZip = new File(filePath);
    zipOut.putNextEntry(new ZipEntry(fileToZip.getName()));
    Files.copy(fileToZip.toPath(), zipOut);
}

Multiple files:

List<String> filePaths = Arrays.asList("/absolute/path/file1.txt", "/absolute/path/file2.txt");
String zipPath = "/absolute/path/output.zip";

try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipPath))) {
    for (String filePath : filePaths) {
        File fileToZip = new File(filePath);
        zipOut.putNextEntry(new ZipEntry(fileToZip.getName()));
        Files.copy(fileToZip.toPath(), zipOut);
    }
}

How to set time to a date object in java

If you don't have access to java 8 and the API java.time, here is my simple function to copy the time of one date to another date using the old java.util.Calendar (inspire by Jigar Joshi) :

/**
 * Copy only the time of one date to the date of another date.
 */
public static Date copyTimeToDate(Date date, Date time) {
    Calendar t = Calendar.getInstance();
    t.setTime(time);

    Calendar c = Calendar.getInstance();
    c.setTime(date);
    c.set(Calendar.HOUR_OF_DAY, t.get(Calendar.HOUR_OF_DAY));
    c.set(Calendar.MINUTE, t.get(Calendar.MINUTE));
    c.set(Calendar.SECOND, t.get(Calendar.SECOND));
    c.set(Calendar.MILLISECOND, t.get(Calendar.MILLISECOND));
    return c.getTime();
}

How to make a text box have rounded corners?

You could use CSS to do that, but it wouldn't be supported in IE8-. You can use some site like http://borderradius.com to come up with actual CSS you'd use, which would look something like this (again, depending on how many browsers you're trying to support):

-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;

How to execute an oracle stored procedure?

Execute is sql*plus syntax .. try wrapping your call in begin .. end like this:

begin 
    temp_proc;
end;

(Although Jeffrey says this doesn't work in APEX .. but you're trying to get this to run in SQLDeveloper .. try the 'Run' menu there.)

How do you set the startup page for debugging in an ASP.NET MVC application?

Revisiting this page and I have more information to share with others.

Debugging environment (using Visual Studio)

1a) Stephen Walter's link to set the startup page on MVC using the project properties is only applicable when you are debugging your MVC application.

1b) Right mouse click on the .aspx page in Solution Explorer and select the "Set As Start Page" behaves the same.

Note: in both the above cases, the startup page setting is only recognised by your Visual Studio Development Server. It is not recognised by your deployed server.

Deployed environment

2a) To set the startup page, assuming that you have not change any of the default routings, change the content of /Views/Home/Index.aspx to do a "Server.Transfer" or a "Response.Redirect" to your desired page.

2b) Change your default routing in your global.asax.cs to your desired page.

Are there any other options that the readers are aware of? Which of the above (including your own option) would be your preferred solution (and please share with us why)?

After installing with pip, "jupyter: command not found"

To be able to run jupyter notebook from terminal, you need to make sure that ~/.local/bin is in your path.

Do this by running export PATH=$PATH:~/.local/bin for your current session, or adding that line to the end of ~/.bashrc to make your changes last for future sessions (e.g. by using nano ~/.bashrc). If you edit ~/.bashrc you will need to log out and log back in to make see your changes take effect.

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0

This normally happens when the transaction is started and either it is not committed or it is not rollback.

In case the error comes in your stored procedure, this can lock the database tables because transaction is not completed due to some runtime errors in the absence of exception handling You can use Exception handling like below. SET XACT_ABORT

SET XACT_ABORT ON
SET NoCount ON
Begin Try 
     BEGIN TRANSACTION 
        //Insert ,update queries    
     COMMIT
End Try 
Begin Catch 
     ROLLBACK
End Catch

Source

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

Using jQuery, Restricting File Size Before Uploading

I tried it this way and I am getting the results in IE*, and Mozilla 3.6.16, didnt check in older versions.

<img id="myImage" src="" style="display:none;"><br>
<button onclick="findSize();">Image Size</button>
<input type="file" id="loadfile" />
<input type="button" value="find size" onclick="findSize()" />
<script type="text/javascript">
function findSize() {
    if ( $.browser.msie ) {
       var a = document.getElementById('loadfile').value;
           $('#myImage').attr('src',a);
           var imgbytes = document.getElementById('myImage').size;
           var imgkbytes = Math.round(parseInt(imgbytes)/1024);
           alert(imgkbytes+' KB');
    }else {
           var fileInput = $("#loadfile")[0];
           var imgbytes = fileInput.files[0].fileSize; // Size returned in bytes.
           var imgkbytes = Math.round(parseInt(imgbytes)/1024);
                   alert(imgkbytes+' KB');
     }
}    
</script>

Add Jquery library also.

Can a normal Class implement multiple interfaces?

A Java class can only extend one parent class. Multiple inheritance (extends) is not allowed. Interfaces are not classes, however, and a class can implement more than one interface.

The parent interfaces are declared in a comma-separated list, after the implements keyword.

In conclusion, yes, it is possible to do:

public class A implements C,D {...}

Explanation of "ClassCastException" in Java

Exception is not a subclass of RuntimeException -> ClassCastException

    final Object  exception = new Exception();
    final Exception data = (RuntimeException)exception ;
    System.out.println(data);

Creating a file only if it doesn't exist in Node.js

What about using the a option?

According to the docs:

'a+' - Open file for reading and appending. The file is created if it does not exist.

It seems to work perfectly with createWriteStream

Calling a java method from c++ in Android

Solution posted by Denys S. in the question post:

I quite messed it up with c to c++ conversion (basically env variable stuff), but I got it working with the following code for C++:

#include <string.h>
#include <stdio.h>
#include <jni.h>

jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){

    jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
    jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
    jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);

    const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
    printf("%s\n", str);

    return (*env)->NewStringUTF(env, str);
}

And next code for java methods:

    public class MainActivity extends Activity {
    private static String LIB_NAME = "thelib";

    static {
        System.loadLibrary(LIB_NAME);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) findViewById(R.id.textview);
        tv.setText(this.getJniString());
    }

    // please, let me live even though I used this dark programming technique
    public String messageMe(String text) {
        System.out.println(text);
        return text;
    }

    public native String getJniString();
}

can't load package: package .: no buildable Go source files

Another possible reason for the message:

can't load package: .... : no buildable Go source files

Is when the source files being compiled have:

// +build ignore

In which case the files are ignored and not buildable as requested.This behaviour is documented at https://golang.org/pkg/go/build/

How to send value attribute from radio button in PHP

Should be :

HTML :

<form method="post" action="">
    <input id="name" name="name" type="text" size="40"/>
    <input type="radio" name="radio" value="test"/>Test
    <input type="submit" name="submit" value="submit"/>
</form>

PHP Code :

if(isset($_POST['submit']))
{

    echo $radio_value = $_POST["radio"];
}

Checkout another branch when there are uncommitted changes on the current branch

Preliminary notes

This answer is an attempt to explain why Git behaves the way it does. It is not a recommendation to engage in any particular workflows. (My own preference is to just commit anyway, avoiding git stash and not trying to be too tricky, but others like other methods.)

The observation here is that, after you start working in branch1 (forgetting or not realizing that it would be good to switch to a different branch branch2 first), you run:

git checkout branch2

Sometimes Git says "OK, you're on branch2 now!" Sometimes, Git says "I can't do that, I'd lose some of your changes."

If Git won't let you do it, you have to commit your changes, to save them somewhere permanent. You may want to use git stash to save them; this is one of the things it's designed for. Note that git stash save or git stash push actually means "Commit all the changes, but on no branch at all, then remove them from where I am now." That makes it possible to switch: you now have no in-progress changes. You can then git stash apply them after switching.

Sidebar: git stash save is the old syntax; git stash push was introduced in Git version 2.13, to fix up some problems with the arguments to git stash and allow for new options. Both do the same thing, when used in the basic ways.

You can stop reading here, if you like!

If Git won't let you switch, you already have a remedy: use git stash or git commit; or, if your changes are trivial to re-create, use git checkout -f to force it. This answer is all about when Git will let you git checkout branch2 even though you started making some changes. Why does it work sometimes, and not other times?

The rule here is simple in one way, and complicated/hard-to-explain in another:

You may switch branches with uncommitted changes in the work-tree if and only if said switching does not require clobbering those changes.

That is—and please note that this is still simplified; there are some extra-difficult corner cases with staged git adds, git rms and such—suppose you are on branch1. A git checkout branch2 would have to do this:

  • For every file that is in branch1 and not in branch2,1 remove that file.
  • For every file that is in branch2 and not in branch1, create that file (with appropriate contents).
  • For every file that is in both branches, if the version in branch2 is different, update the working tree version.

Each of these steps could clobber something in your work-tree:

  • Removing a file is "safe" if the version in the work-tree is the same as the committed version in branch1; it's "unsafe" if you've made changes.
  • Creating a file the way it appears in branch2 is "safe" if it does not exist now.2 It's "unsafe" if it does exist now but has the "wrong" contents.
  • And of course, replacing the work-tree version of a file with a different version is "safe" if the work-tree version is already committed to branch1.

Creating a new branch (git checkout -b newbranch) is always considered "safe": no files will be added, removed, or altered in the work-tree as part of this process, and the index/staging-area is also untouched. (Caveat: it's safe when creating a new branch without changing the new branch's starting-point; but if you add another argument, e.g., git checkout -b newbranch different-start-point, this might have to change things, to move to different-start-point. Git will then apply the checkout safety rules as usual.)


1This requires that we define what it means for a file to be in a branch, which in turn requires defining the word branch properly. (See also What exactly do we mean by "branch"?) Here, what I really mean is the commit to which the branch-name resolves: a file whose path is P is in branch1 if git rev-parse branch1:P produces a hash. That file is not in branch1 if you get an error message instead. The existence of path P in your index or work-tree is not relevant when answering this particular question. Thus, the secret here is to examine the result of git rev-parse on each branch-name:path. This either fails because the file is "in" at most one branch, or gives us two hash IDs. If the two hash IDs are the same, the file is the same in both branches. No changing is required. If the hash IDs differ, the file is different in the two branches, and must be changed to switch branches.

The key notion here is that files in commits are frozen forever. Files you will edit are obviously not frozen. We are, at least initially, looking only at the mismatches between two frozen commits. Unfortunately, we—or Git—also have to deal with files that aren't in the commit you're going to switch away from and are in the commit you're going to switch to. This leads to the remaining complications, since files can also exist in the index and/or in the work-tree, without having to exist these two particular frozen commits we're working with.

2It might be considered "sort-of-safe" if it already exists with the "right contents", so that Git does not have to create it after all. I recall at least some versions of Git allowing this, but testing just now shows it to be considered "unsafe" in Git 1.8.5.4. The same argument would apply to a modified file that happens to be modified to match the to-be-switch-to branch. Again, 1.8.5.4 just says "would be overwritten", though. See the end of the technical notes as well: my memory may be faulty as I don't think the read-tree rules have changed since I first started using Git at version 1.5.something.


Does it matter whether the changes are staged or unstaged?

Yes, in some ways. In particular, you can stage a change, then "de-modify" the work tree file. Here's a file in two branches, that's different in branch1 and branch2:

$ git show branch1:inboth
this file is in both branches
$ git show branch2:inboth
this file is in both branches
but it has more stuff in branch2 now
$ git checkout branch1
Switched to branch 'branch1'
$ echo 'but it has more stuff in branch2 now' >> inboth

At this point, the working tree file inboth matches the one in branch2, even though we're on branch1. This change is not staged for commit, which is what git status --short shows here:

$ git status --short
 M inboth

The space-then-M means "modified but not staged" (or more precisely, working-tree copy differs from staged/index copy).

$ git checkout branch2
error: Your local changes ...

OK, now let's stage the working-tree copy, which we already know also matches the copy in branch2.

$ git add inboth
$ git status --short
M  inboth
$ git checkout branch2
Switched to branch 'branch2'

Here the staged-and-working copies both matched what was in branch2, so the checkout was allowed.

Let's try another step:

$ git checkout branch1
Switched to branch 'branch1'
$ cat inboth
this file is in both branches

The change I made is lost from the staging area now (because checkout writes through the staging area). This is a bit of a corner case. The change is not gone, but the fact that I had staged it, is gone.

Let's stage a third variant of the file, different from either branch-copy, then set the working copy to match the current branch version:

$ echo 'staged version different from all' > inboth
$ git add inboth
$ git show branch1:inboth > inboth
$ git status --short
MM inboth

The two Ms here mean: staged file differs from HEAD file, and, working-tree file differs from staged file. The working-tree version does match the branch1 (aka HEAD) version:

$ git diff HEAD
$

But git checkout won't allow the checkout:

$ git checkout branch2
error: Your local changes ...

Let's set the branch2 version as the working version:

$ git show branch2:inboth > inboth
$ git status --short
MM inboth
$ git diff HEAD
diff --git a/inboth b/inboth
index ecb07f7..aee20fb 100644
--- a/inboth
+++ b/inboth
@@ -1 +1,2 @@
 this file is in both branches
+but it has more stuff in branch2 now
$ git diff branch2 -- inboth
$ git checkout branch2
error: Your local changes ...

Even though the current working copy matches the one in branch2, the staged file does not, so a git checkout would lose that copy, and the git checkout is rejected.

Technical notes—only for the insanely curious :-)

The underlying implementation mechanism for all of this is Git's index. The index, also called the "staging area", is where you build the next commit: it starts out matching the current commit, i.e., whatever you have checked-out now, and then each time you git add a file, you replace the index version with whatever you have in your work-tree.

Remember, the work-tree is where you work on your files. Here, they have their normal form, rather than some special only-useful-to-Git form like they do in commits and in the index. So you extract a file from a commit, through the index, and then on into the work-tree. After changing it, you git add it to the index. So there are in fact three places for each file: the current commit, the index, and the work-tree.

When you run git checkout branch2, what Git does underneath the covers is to compare the tip commit of branch2 to whatever is in both the current commit and the index now. Any file that matches what's there now, Git can leave alone. It's all untouched. Any file that's the same in both commits, Git can also leave alone—and these are the ones that let you switch branches.

Much of Git, including commit-switching, is relatively fast because of this index. What's actually in the index is not each file itself, but rather each file's hash. The copy of the file itself is stored as what Git calls a blob object, in the repository. This is similar to how the files are stored in commits as well: commits don't actually contain the files, they just lead Git to the hash ID of each file. So Git can compare hash IDs—currently 160-bit-long strings—to decide if commits X and Y have the same file or not. It can then compare those hash IDs to the hash ID in the index, too.

This is what leads to all the oddball corner cases above. We have commits X and Y that both have file path/to/name.txt, and we have an index entry for path/to/name.txt. Maybe all three hashes match. Maybe two of them match and one doesn't. Maybe all three are different. And, we might also have another/file.txt that's only in X or only in Y and is or is not in the index now. Each of these various cases requires its own separate consideration: does Git need to copy the file out from commit to index, or remove it from index, to switch from X to Y? If so, it also has to copy the file to the work-tree, or remove it from the work-tree. And if that's the case, the index and work-tree versions had better match at least one of the committed versions; otherwise Git will be clobbering some data.

(The complete rules for all of this are described in, not the git checkout documentation as you might expect, but rather the git read-tree documentation, under the section titled "Two Tree Merge".)

To check if string contains particular word

Using contains

String sentence = "Check this answer and you can find the keyword with this code";
String search = "keyword";

if (sentence.toLowerCase().contains(search.toLowerCase())) {

  System.out.println("I found the keyword..!");

} else {

  System.out.println("not found..!");

}

Are (non-void) self-closing tags valid in HTML5?

As Nikita Skvortsov pointed out, a self-closing div will not validate. This is because a div is a normal element, not a void element.

According to the HTML5 spec, tags that cannot have any contents (known as void elements) can be self-closing*. This includes the following tags:

area, base, br, col, embed, hr, img, input, 
keygen, link, meta, param, source, track, wbr

The "/" is completely optional on the above tags, however, so <img/> is not different from <img>, but <img></img> is invalid.

*Note: foreign elements can also be self-closing, but I don't think that's in scope for this answer.

.append(), prepend(), .after() and .before()

append() & prepend() are for inserting content inside an element (making the content its child) while after() & before() insert content outside an element (making the content its sibling).

How to open a different activity on recyclerView item onclick

you can implement your adapter's onClickListener:

  public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder>implements View.OnClickListener

and use interface with method in it

public interface mClickListener {
    public void mClick(View v, int position);
}

and in your onClick method call the method in the interface and pass it the view and position

in your main activity implement that interface

public class MainActivity extends ActionBarActivity implements AdapterClass.mClickListener

and override that method

@Override
public void onCommentsClick(View v, int position) {
    final Intent intent = new Intent(this, OtherActivity.class);
}

as its better to manage your activity transition by the activity not other classes

Download a specific tag with Git

first fetch all the tags in that specific remote

git fetch <remote> 'refs/tags/*:refs/tags/*'

or just simply type

git fetch <remote>

Then check for the available tags

git tag -l

then switch to that specific tag using below command

git checkout tags/<tag_name>

Hope this will helps you!

How to download Google Play Services in an Android emulator?

The key is to select the target of your emulator to, for example: Google APIs (ver 18). If you select, for example, just Jellybean 18 (without API) you will not be able to test apps that require Google services such as map. Keep in mind that you must first download the Google API of your favorite version with the Android SDK Manager.

This is a good practice and it is far better than juggling with most workarounds.

How to get the last element of a slice?

For just reading the last element of a slice:

sl[len(sl)-1]

For removing it:

sl = sl[:len(sl)-1]

See this page about slice tricks

Is there a way I can capture my iPhone screen as a video?

As others have suggested, AirPlay mirroring is the way to go. To mirror directly to your computer use an AirPlay server like http://www.airserverapp.com/. Then, since it's showing up directly on your computer you can capture it using the built-in Quicktime app (File > New Screen Recording). Works great!

Convert array of JSON object strings to array of JS objects

var json = jQuery.parseJSON(s); //If you have jQuery.

Since the comment looks cluttered, please use the parse function after enclosing those square brackets inside the quotes.

var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];

Change the above code to

var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

Eg:

$(document).ready(function() {
    var s= '[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

    s = jQuery.parseJSON(s);

    alert( s[0]["Select"] );
});

And then use the parse function. It'll surely work.

EDIT :Extremely sorry that I gave the wrong function name. it's jQuery.parseJSON

Jquery

The json api

Edit (30 April 2020):

Editing since I got an upvote for this answer. There's a browser native function available instead of JQuery (for nonJQuery users), JSON.parse("<json string here>")

Reset ID autoincrement ? phpmyadmin

You can also do this in phpMyAdmin without writing SQL.

  • Click on a database name in the left column.
  • Click on a table name in the left column.
  • Click the "Operations" tab at the top.
  • Under "Table options" there should be a field for AUTO_INCREMENT (only on tables that have an auto-increment field).
  • Input desired value and click the "Go" button below.

Note: You'll see that phpMyAdmin is issuing the same SQL that is mentioned in the other answers.

How do I hide certain files from the sidebar in Visual Studio Code?

I would also like to recommend vscode extension Peep, which allows you to toggle hide on the excluded files in your projects settings.json.

Hit F1 for vscode command line (command palette), then

ext install [enter] peep [enter]

You can bind "extension.peepToggle" to a key like Ctrl+Shift+P (same as F1 by default) for easy toggling. Hit Ctrl+K Ctrl+S for key bindings, enter peep, select Peep Toggle and add your binding.

C# "internal" access modifier when doing unit testing

If you want to test private methods, have a look at PrivateObject and PrivateType in the Microsoft.VisualStudio.TestTools.UnitTesting namespace. They offer easy to use wrappers around the necessary reflection code.

Docs: PrivateType, PrivateObject

For VS2017 & 2019, you can find these by downloading the MSTest.TestFramework nuget

SmtpException: Unable to read data from the transport connection: net_io_connectionclosed

You may also have to change the "less secure apps" setting on your Gmail account. EnableSsl, use port 587 and enable "less secure apps". If you google the less secure apps part there are google help pages that will link you right to the page for your account. That was my problem but everything is working now thanks to all the answers above.

Text not wrapping in p tag

For others that find themselves here, the css I was looking for was

overflow-wrap: break-word;

Which will only break a word if it needs to (the length of the single word is greater than the width of the p), unlike word-break: break-all which can break the last word of every line.

overflow-wrap demo

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

Perhaps you can try some jQuery like this:

if ($.browser.msie && $.browser.version === 10) {
  $("html").addClass("ie10");
}

To use this method you must include the jQuery Migrate library because this function was removed from the main jQuery library.

Worked out quite fine for me. But surely no replacement for conditional comments!

Tkinter understanding mainloop

while 1:
    root.update()

... is (very!) roughly similar to:

root.mainloop()

The difference is, mainloop is the correct way to code and the infinite loop is subtly incorrect. I suspect, though, that the vast majority of the time, either will work. It's just that mainloop is a much cleaner solution. After all, calling mainloop is essentially this under the covers:

while the_window_has_not_been_destroyed():
    wait_until_the_event_queue_is_not_empty()
    event = event_queue.pop()
    event.handle()

... which, as you can see, isn't much different than your own while loop. So, why create your own infinite loop when tkinter already has one you can use?

Put in the simplest terms possible: always call mainloop as the last logical line of code in your program. That's how Tkinter was designed to be used.

mssql '5 (Access is denied.)' error during restoring database

A good solution that can work is go to files > and check the reallocate all files

Files relocate

Changing the action of a form with JavaScript/jQuery

just to add a detail to what Tamlyn wrote, instead of
$('form').get(0).setAttribute('action', 'baz'); //this works

$('form')[0].setAttribute('action', 'baz');
works equally well

Property getters and setters

You can customize the set value using property observer. To do this use 'didSet' instead of 'set'.

class Point {

var x: Int {
    didSet {
        x = x * 2
    }
}
...

As for getter ...

class Point {

var doubleX: Int {
    get {
        return x / 2
    }
}
...

Simplest way to throw an error/exception with a custom message in Swift 2?

Swift 4:

As per:

https://developer.apple.com/documentation/foundation/nserror

if you don't want to define a custom exception, you could use a standard NSError object as follows:

import Foundation

do {
  throw NSError(domain: "my error domain", code: 42, userInfo: ["ui1":12, "ui2":"val2"] ) 
}
catch let error as NSError {
  print("Caught NSError: \(error.localizedDescription), \(error.domain), \(error.code)")
  let uis = error.userInfo 
  print("\tUser info:")
  for (key,value) in uis {
    print("\t\tkey=\(key), value=\(value)")
  }
}

Prints:

Caught NSError: The operation could not be completed, my error domain, 42
    User info:
        key=ui1, value=12
        key=ui2, value=val2

This allows you to provide a custom string (the error domain), plus a numeric code and a dictionary with all the additional data you need, of any type.

N.B.: this was tested on OS=Linux (Ubuntu 16.04 LTS).

Removing whitespace between HTML elements when using line breaks

Semantically speaking, wouldn't it be best to use an ordered or unordered list and then style it appropriately using CSS?

<ul id="[UL_ID]">
    <li><img src="[image1_url]" alt="img1" /></li>
    <li><img src="[image2_url]" alt="img2" /></li>
    <li><img src="[image3_url]" alt="img3" /></li>
    <li><img src="[image4_url]" alt="img4" /></li>
    <li><img src="[image5_url]" alt="img5" /></li>
    <li><img src="[image6_url]" alt="img6" /></li>
</ul>

Using CSS, you'll be able to style this whatever way you want and remove the whitespace imbetween the books.

Excel VBA Macro: User Defined Type Not Defined

Sub DeleteEmptyRows()  

    Worksheets("YourSheetName").Activate
    On Error Resume Next
    Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

End Sub

The following code will delete all rows on a sheet(YourSheetName) where the content of Column A is blank.

EDIT: User Defined Type Not Defined is caused by "oTable As Table" and "oRow As Row". Replace Table and Row with Object to resolve the error and make it compile.

How to turn on front flash light programmatically in Android?

You can also use the following code to turn off the flash.

Camera.Parameters params = mCamera.getParameters()
p.setFlashMode(Parameters.FLASH_MODE_OFF);
mCamera.setParameters(params);

Running Command Line in Java

Have you tried the exec command within the Runtime class?

Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug")

Runtime - Java Documentation

Java Swing - how to show a panel on top of another panel?

Use a 1 by 1 GridLayout on the existing JPanel, then add your Panel to that JPanel. The only problem with a GridLayout that's 1 by 1 is that you won't be able to place other items on the JPanel. In this case, you will have to figure out a layout that is suitable. Each panel that you use can use their own layout so that wouldn't be a problem.

Am I understanding this question correctly?

Span inside anchor or anchor inside span or doesn't matter?

It doesn't matter - they're both allowed inside each other.

How do I get the type of a variable?

For static assertions, C++11 introduced decltype which is quite useful in certain scenarios.

How to initialize a two-dimensional array in Python?

Matrix={}
for i in range(0,3):
  for j in range(0,3):
    Matrix[i,j] = raw_input("Enter the matrix:")

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

Environment variables (that you modify using the System Properties) are only propagated to subshells when you create a new subshell.

If you had a command line prompt (DOS or cygwin) open when you changed the User env vars, then they won't show up.

You need to open a new command line prompt after you change the user settings.

The equivalent in Unix/Linux is adding a line to your .bash_rc: you need to start a new shell to get the values.

PHP string concatenation

Just use . for concatenating. And you missed out the $personCount increment!

while ($personCount < 10) {
    $result .= $personCount . ' people';
    $personCount++;
}

echo $result;

combining results of two select statements

Probably you use Microsoft SQL Server which support Common Table Expressions (CTE) (see http://msdn.microsoft.com/en-us/library/ms190766.aspx) which are very friendly for query optimization. So I suggest you my favor construction:

WITH GetNumberOfPlans(Id,NumberOfPlans) AS (
    SELECT tableA.Id, COUNT(tableC.Id)
    FROM tableC
        RIGHT OUTER JOIN tableA ON tableC.tableAId = tableA.Id
    GROUP BY tableA.Id
),GetUserInformation(Id,Name,Owner,ImageUrl,
                     CompanyImageUrl,NumberOfUsers) AS (
    SELECT tableA.Id, tableA.Name, tableB.Username AS Owner, tableB.ImageUrl,
        tableB.CompanyImageUrl,COUNT(tableD.UserId),p.NumberOfPlans
    FROM tableA
        INNER JOIN tableB ON tableB.Id = tableA.Owner
        RIGHT OUTER JOIN tableD ON tableD.tableAId = tableA.Id
    GROUP BY tableA.Name, tableB.Username, tableB.ImageUrl, tableB.CompanyImageUrl
)
SELECT u.Id,u.Name,u.Owner,u.ImageUrl,u.CompanyImageUrl
    ,u.NumberOfUsers,p.NumberOfPlans
FROM GetUserInformation AS u
    INNER JOIN GetNumberOfPlans AS p ON p.Id=u.Id

After some experiences with CTE you will be find very easy to write code using CTE and you will be happy with the performance.

Equivalent of *Nix 'which' command in PowerShell?

The very first alias I made once I started customizing my profile in PowerShell was 'which'.

New-Alias which get-command

To add this to your profile, type this:

"`nNew-Alias which get-command" | add-content $profile

The `n at the start of the last line is to ensure it will start as a new line.

How can I write a byte array to a file in Java?

As Sebastian Redl points out the most straight forward now java.nio.file.Files.write. Details for this can be found in the Reading, Writing, and Creating Files tutorial.


Old answer: FileOutputStream.write(byte[]) would be the most straight forward. What is the data you want to write?

The tutorials for Java IO system may be of some use to you.

pass JSON to HTTP POST Request

       var request = require('request');
        request({
            url: "http://localhost:8001/xyz",
            json: true,
            headers: {
                "content-type": "application/json",
            },
            body: JSON.stringify(requestData)
        }, function(error, response, body) {
            console.log(response);
        });

tkinter: how to use after method

You need to give a function to be called after the time delay as the second argument to after:

after(delay_ms, callback=None, *args)

Registers an alarm callback that is called after a given time.

So what you really want to do is this:

tiles_letter = ['a', 'b', 'c', 'd', 'e']

def add_letter():
    rand = random.choice(tiles_letter)
    tile_frame = Label(frame, text=rand)
    tile_frame.pack()
    root.after(500, add_letter)
    tiles_letter.remove(rand)  # remove that tile from list of tiles


root.after(0, add_letter)  # add_letter will run as soon as the mainloop starts.
root.mainloop()

You also need to schedule the function to be called again by repeating the call to after inside the callback function, since after only executes the given function once. This is also noted in the documentation:

The callback is only called once for each call to this method. To keep calling the callback, you need to reregister the callback inside itself

Note that your example will throw an exception as soon as you've exhausted all the entries in tiles_letter, so you need to change your logic to handle that case whichever way you want. The simplest thing would be to add a check at the beginning of add_letter to make sure the list isn't empty, and just return if it is:

def add_letter():
    if not tiles_letter:
        return
    rand = random.choice(tiles_letter)
    tile_frame = Label(frame, text=rand)
    tile_frame.pack()
    root.after(500, add_letter)
    tiles_letter.remove(rand)  # remove that tile from list of tiles

Live-Demo: repl.it

When to use RabbitMQ over Kafka?

The short answer is "message acknowledgements". RabbitMQ can be configured to require message acknowledgements. If a receiver fails the message goes back on the queue and another receiver can try again. While you can accomplish this in Kafka with your own code, it works with RabbitMQ out of the box.

In my experience, if you have an application that has requirements to query a stream of information, Kafka and KSql are your best bet. If you want a queueing system you are better off with RabbitMQ.

Python: json.loads returns items prefixing with 'u'

Everything is cool, man. The 'u' is a good thing, it indicates that the string is of type Unicode in python 2.x.

http://docs.python.org/2/howto/unicode.html#the-unicode-type

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

How to convert integer to decimal in SQL Server query?

declare @xx int 
set     @xx = 3 
select @xx      
select @xx * 2  -- yields another integer  
select @xx/1    -- same
select @xx/1.0  --yields 6 decimal places 
select @xx/1.00 --       6 
select @xx * 1.0  --     1 decimal place - victory
select @xx * 1.00 --     2         places - hooray 

Also _ inserting an int into a temp_table with like decimal(10,3) _ works ok.

How to find the process id of a running Java process on Windows? And how to kill the process alone?

This will work even when there are multiple instance of jar is running

wmic Path win32_process Where "CommandLine Like '%yourname.jar%'" Call Terminate

How to split a string, but also keep the delimiters?

One of the subtleties in this question involves the "leading delimiter" question: if you are going to have a combined array of tokens and delimiters you have to know whether it starts with a token or a delimiter. You could of course just assume that a leading delim should be discarded but this seems an unjustified assumption. You might also want to know whether you have a trailing delim or not. This sets two boolean flags accordingly.

Written in Groovy but a Java version should be fairly obvious:

            String tokenRegex = /[\p{L}\p{N}]+/ // a String in Groovy, Unicode alphanumeric
            def finder = phraseForTokenising =~ tokenRegex
            // NB in Groovy the variable 'finder' is then of class java.util.regex.Matcher
            def finderIt = finder.iterator() // extra method added to Matcher by Groovy magic
            int start = 0
            boolean leadingDelim, trailingDelim
            def combinedTokensAndDelims = [] // create an array in Groovy

            while( finderIt.hasNext() )
            {
                def token = finderIt.next()
                int finderStart = finder.start()
                String delim = phraseForTokenising[ start  .. finderStart - 1 ]
                // Groovy: above gets slice of String/array
                if( start == 0 ) leadingDelim = finderStart != 0
                if( start > 0 || leadingDelim ) combinedTokensAndDelims << delim
                combinedTokensAndDelims << token // add element to end of array
                start = finder.end()
            }
            // start == 0 indicates no tokens found
            if( start > 0 ) {
                // finish by seeing whether there is a trailing delim
                trailingDelim = start < phraseForTokenising.length()
                if( trailingDelim ) combinedTokensAndDelims << phraseForTokenising[ start .. -1 ]

                println( "leading delim? $leadingDelim, trailing delim? $trailingDelim, combined array:\n $combinedTokensAndDelims" )

            }

how to check for null with a ng-if values in a view with angularjs?

See the correct way with your example:

<div ng-if="!test.view">1</div>
<div ng-if="!!test.view">2</div>

Regards, Nicholls

How to format DateTime to 24 hours time?

Use upper-case HH for 24h format:

String s = curr.ToString("HH:mm");

See DateTime.ToString Method.

Android: Color To Int conversion

Any color parse into int simplest two way here:

1) Get System Color

int redColorValue = Color.RED;

2) Any Color Hex Code as a String Argument

int greenColorValue = Color.parseColor("#00ff00")

MUST REMEMBER in above code Color class must be android.graphics...!

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

I had problems using pdftk with the cat parameter had a better success with output.

The following command worked for me:

pdftk file_1.pdf file_1.pdf file_1.pdf file_1.pdf cat output.pdf

Using cat produced the following error:

Error: Unexpected text in page range end, here: 
    output.pdf
    Exiting.
    Acceptable keywords, for example: "even" or "odd".
    To rotate pages, use: "north" "south" "east"
        "west" "left" "right" or "down"
Errors encountered.  No output created.
Done.  Input errors, so no output created.

http://www.pdflabs.com/docs/pdftk-cli-examples/.

I created a 172mb PDF is no time at all.

What are C++ functors and their uses?

To add on, I have used function objects to fit an existing legacy method to the command pattern; (only place where the beauty of OO paradigm true OCP I felt ); Also adding here the related function adapter pattern.

Suppose your method has the signature:

int CTask::ThreeParameterTask(int par1, int par2, int par3)

We will see how we can fit it for the Command pattern - for this, first, you have to write a member function adapter so that it can be called as a function object.

Note - this is ugly, and may be you can use the Boost bind helpers etc., but if you can't or don't want to, this is one way.

// a template class for converting a member function of the type int        function(int,int,int)
//to be called as a function object
template<typename _Ret,typename _Class,typename _arg1,typename _arg2,typename _arg3>
class mem_fun3_t
{
  public:
explicit mem_fun3_t(_Ret (_Class::*_Pm)(_arg1,_arg2,_arg3))
    :m_Ptr(_Pm) //okay here we store the member function pointer for later use
    {}

//this operator call comes from the bind method
_Ret operator()(_Class *_P, _arg1 arg1, _arg2 arg2, _arg3 arg3) const
{
    return ((_P->*m_Ptr)(arg1,arg2,arg3));
}
private:
_Ret (_Class::*m_Ptr)(_arg1,_arg2,_arg3);// method pointer signature
};

Also, we need a helper method mem_fun3 for the above class to aid in calling.

template<typename _Ret,typename _Class,typename _arg1,typename _arg2,typename _arg3>
mem_fun3_t<_Ret,_Class,_arg1,_arg2,_arg3> mem_fun3 ( _Ret (_Class::*_Pm)          (_arg1,_arg2,_arg3) )
{
  return (mem_fun3_t<_Ret,_Class,_arg1,_arg2,_arg3>(_Pm));
}

Now, in order to bind the parameters, we have to write a binder function. So, here it goes:

template<typename _Func,typename _Ptr,typename _arg1,typename _arg2,typename _arg3>
class binder3
{
public:
//This is the constructor that does the binding part
binder3(_Func fn,_Ptr ptr,_arg1 i,_arg2 j,_arg3 k)
    :m_ptr(ptr),m_fn(fn),m1(i),m2(j),m3(k){}

 //and this is the function object 
 void operator()() const
 {
        m_fn(m_ptr,m1,m2,m3);//that calls the operator
    }
private:
    _Ptr m_ptr;
    _Func m_fn;
    _arg1 m1; _arg2 m2; _arg3 m3;
};

And, a helper function to use the binder3 class - bind3:

//a helper function to call binder3
template <typename _Func, typename _P1,typename _arg1,typename _arg2,typename _arg3>
binder3<_Func, _P1, _arg1, _arg2, _arg3> bind3(_Func func, _P1 p1,_arg1 i,_arg2 j,_arg3 k)
{
    return binder3<_Func, _P1, _arg1, _arg2, _arg3> (func, p1,i,j,k);
}

Now, we have to use this with the Command class; use the following typedef:

typedef binder3<mem_fun3_t<int,T,int,int,int> ,T* ,int,int,int> F3;
//and change the signature of the ctor
//just to illustrate the usage with a method signature taking more than one parameter
explicit Command(T* pObj,F3* p_method,long timeout,const char* key,
long priority = PRIO_NORMAL ):
m_objptr(pObj),m_timeout(timeout),m_key(key),m_value(priority),method1(0),method0(0),
method(0)
{
    method3 = p_method;
}

Here is how you call it:

F3 f3 = PluginThreadPool::bind3( PluginThreadPool::mem_fun3( 
      &CTask::ThreeParameterTask), task1,2122,23 );

Note: f3(); will call the method task1->ThreeParameterTask(21,22,23);.

The full context of this pattern at the following link

sql server #region

I've used a technique similar to McVitie's, and only in stored procedures or scripts that are pretty long. I will break down certain functional portions like this:

BEGIN /** delete queries **/

DELETE FROM blah_blah

END /** delete queries **/

BEGIN /** update queries **/

UPDATE sometable SET something = 1

END /** update queries **/

This method shows up fairly nice in management studio and is really helpful in reviewing code. The collapsed piece looks sort of like:

BEGIN /** delete queries **/ ... /** delete queries **/

I actually prefer it this way because I know that my BEGIN matches with the END this way.

dropdownlist set selected value in MVC3 Razor

I drilled down the formation of the drop down list instead of using @Html.DropDownList(). This is useful if you have to set the value of the dropdown list at runtime in razor instead of controller:

<select id="NewsCategoriesID" name="NewsCategoriesID">
    @foreach (SelectListItem option in ViewBag.NewsCategoriesID)
    {
        <option value="@option.Value" @(option.Value == ViewBag.ValueToSet ? "selected='selected'" : "")>@option.Text</option>

    }
</select>

vi/vim editor, copy a block (not usual action)

It sounds like you want to place marks in the file.

mx places a mark named x under the cursor

y'x yanks everything between the cursor's current position and the line containing mark x.

You can use 'x to simply move the cursor to the line with your mark.

You can use `x (a back-tick) to move to the exact location of the mark.


One thing I do all the time is yank everything between the cursor and mark x into the clipboard.

You can do that like this:

"+y'x

NOTE: In some environments the clipboard buffer is represented by a * in stead of a +.


Similar questions with some good answers:

How do I get total physical memory size using PowerShell without WMI?

Let's not over complicate things...:

(Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum).sum /1gb

Is optimisation level -O3 dangerous in g++?

In my somewhat checkered experience, applying -O3 to an entire program almost always makes it slower (relative to -O2), because it turns on aggressive loop unrolling and inlining that make the program no longer fit in the instruction cache. For larger programs, this can also be true for -O2 relative to -Os!

The intended use pattern for -O3 is, after profiling your program, you manually apply it to a small handful of files containing critical inner loops that actually benefit from these aggressive space-for-speed tradeoffs. Newer versions of GCC have a profile-guided optimization mode that can (IIUC) selectively apply the -O3 optimizations to hot functions -- effectively automating this process.

Multiple conditions in an IF statement in Excel VBA

In VBA we can not use if jj = 5 or 6 then we must use if jj = 5 or jj = 6 then

maybe this:

If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then

How to edit hosts file via CMD?

Use Hosts Commander. It's simple and powerful. Translated description (from russian) here.

Examples of using

hosts add another.dev 192.168.1.1 # Remote host
hosts add test.local # 127.0.0.1 used by default
hosts set myhost.dev # new comment
hosts rem *.local
hosts enable local*
hosts disable localhost

...and many others...

Help

Usage:
    hosts - run hosts command interpreter
    hosts <command> <params> - execute hosts command

Commands:
    add  <host> <aliases> <addr> # <comment>   - add new host
    set  <host|mask> <addr> # <comment>        - set ip and comment for host
    rem  <host|mask>   - remove host
    on   <host|mask>   - enable host
    off  <host|mask>   - disable host
    view [all] <mask>  - display enabled and visible, or all hosts
    hide <host|mask>   - hide host from 'hosts view'
    show <host|mask>   - show host in 'hosts view'
    print      - display raw hosts file
    format     - format host rows
    clean      - format and remove all comments
    rollback   - rollback last operation
    backup     - backup hosts file
    restore    - restore hosts file from backup
    recreate   - empty hosts file
    open       - open hosts file in notepad

Download

https://code.google.com/p/hostscmd/downloads/list

Algorithm to randomly generate an aesthetically-pleasing color palette

David Crow's method in an R two-liner:

GetRandomColours <- function(num.of.colours, color.to.mix=c(1,1,1)) {
  return(rgb((matrix(runif(num.of.colours*3), nrow=num.of.colours)*color.to.mix)/2))
}

How can I stop a running MySQL query?

mysql>show processlist;

mysql> kill "number from first col";

Can you append strings to variables in PHP?

This is because PHP uses the period character . for string concatenation, not the plus character +. Therefore to append to a string you want to use the .= operator:

for ($i=1;$i<=100;$i++)
{
    $selectBox .= '<option value="' . $i . '">' . $i . '</option>';
}
$selectBox .= '</select>';

Java : Comparable vs Comparator

When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.

A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.

For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.

In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.

Regular Expression for password validation

Update to Justin answer above. if you want to use it using Data Annotation in MVC you can do as follow

[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}$", ErrorMessage = "Password must be between 6 and 20 characters and contain one uppercase letter, one lowercase letter, one digit and one special character.")]

Find size of Git repository

Note that, since git 1.8.3 (April, 22d 2013):

"git count-objects" learned "--human-readable" aka "-H" option to show various large numbers in Ki/Mi/GiB scaled as necessary.

That could be combined with the -v option mentioned by Jack Morrison in his answer.

git gc
git count-objects -vH

(git gc is important, as mentioned by A-B-B's answer)

Plus (still git 1.8.3), the output is more complete:

"git count-objects -v" learned to report leftover temporary packfiles and other garbage in the object store.

Chrome/jQuery Uncaught RangeError: Maximum call stack size exceeded

You can also get this error when you have an infinite loop. Make sure that you don't have any unending, recursive self references.

How to hide elements without having them take space on the page?

Thanks to this question. I wanted the exact opposite, i.e a hidden div should still occupy its space on the browser. So, I used visibility: hidden instead of display: none.

Combining multiple commits before pushing in Git

You can squash (join) commits with an Interactive Rebase. There is a pretty nice YouTube video which shows how to do this on the command line or with SmartGit:

If you are already a SmartGit user then you can select all your outgoing commits (by holding down the Ctrl key) and open the context menu (right click) to squash your commits.

It's very comfortable:

enter image description here

There is also a very nice tutorial from Atlassian which shows how it works:

PHP array: count or sizeof?

They are identical according to sizeof()

In the absence of any reason to worry about "faster", always optimize for the human. Which makes more sense to the human reader?

Printing integer variable and string on same line in SQL

You can't combine a character string and numeric string. You need to convert the number to a string using either CONVERT or CAST.

For example:

print 'There are ' + cast(@Number as varchar) + ' alias combinations did not match a record'

or

print 'There are ' + convert(varchar,@Number) + ' alias combinations did not match a record'

wget command to download a file and save as a different filename

wget -O yourfilename.zip remote-storage.url/theirfilename.zip

will do the trick for you.

Note:

a) its a capital O.

b) wget -O filename url will only work. Putting -O last will not.

Add click event on div tag using javascript

Try this:

 var div = document.getElementsByClassName('drill_cursor')[0];

 div.addEventListener('click', function (event) {
     alert('Hi!');
 });

CSS Div width percentage and padding without breaking layout

If you want the #header to be the same width as your container, with 10px of padding, you can leave out its width declaration. That will cause it to implicitly take up its entire parent's width (since a div is by default a block level element).

Then, since you haven't defined a width on it, the 10px of padding will be properly applied inside the element, rather than adding to its width:

#container {
    position: relative;
    width: 80%;
}

#header {
    position: relative;
    height: 50px;
    padding: 10px;
}

You can see it in action here.

The key when using percentage widths and pixel padding/margins is not to define them on the same element (if you want to accurately control the size). Apply the percentage width to the parent and then the pixel padding/margin to a display: block child with no width set.


Update

Another option for dealing with this is to use the box-sizing CSS rule:

#container { 
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */

    /* Since this element now uses border-box sizing, the 10px of horizontal
       padding will be drawn inside the 80% width */
    width: 80%;
    padding: 0 10px;
}

Here's a post talking about how box-sizing works.

Can you force Visual Studio to always run as an Administrator in Windows 8?

Just find the program in Program Files directory (or in other location). Right click on the EXE file, on the second tab at the bottom check the checkbox of forcing running that program with administration privileges. From now all shortcuts of the exe file will be fired with administration privileges :)

jQuery plugin returning "Cannot read property of undefined"

The problem is that "i" is incremented, so by the time the click event is executed the value of i equals len. One possible solution is to capture the value of i inside a function:

var len = menuitems.length;
for (var i = 0; i < len; i++){
    (function(i) {
      $('<li/>',{
          'html':'<img src="'+menuitems[i].icon+'">'+menuitems[i].name,
          'click':function(){
              menuitems[i].action();
          },
          'class':o.itemClass
      }).appendTo('.'+o.listClass);
    })(i);
}

In the above sample, the anonymous function creates a new scope which captures the current value of i, so that when the click event is triggered the local variable is used instead of the i from the for loop.

Is there an easy way to return a string repeated X number of times?

I didn't see this solution. I find it simpler for where I currently am in software development:

public static void PrintFigure(int shapeSize)
{
    string figure = "\\/";
    for (int loopTwo = 1; loopTwo <= shapeSize - 1; loopTwo++)
    {
        Console.Write($"{figure}");
    }
}

PHP CSV string to array

A modification of previous answers using array_map.
Blow up the CSV data with multiple lines.

$csv = array_map('str_getcsv', explode("\n", $csvData));

How to check whether a select box is empty using JQuery/Javascript

To check whether select box has any values:

if( $('#fruit_name').has('option').length > 0 ) {

To check whether selected value is empty:

if( !$('#fruit_name').val() ) { 

Freemarker iterating over hashmap keys

Since 2.3.25, do it like this:

<#list user as propName, propValue>
  ${propName} = ${propValue}
</#list>

Note that this also works with non-string keys (unlike map[key], which had to be written as map?api.get(key) then).

Before 2.3.25 the standard solution was:

<#list user?keys as prop>
  ${prop} = ${user[prop]}
</#list>

However, some really old FreeMarker integrations use a strange configuration, where the public Map methods (like getClass) appear as keys. That happens as they are using a pure BeansWrapper (instead of DefaultObjectWrapper) whose simpleMapWrapper property was left on false. You should avoid such a setup, as it mixes the methods with real Map entries. But if you run into such unfortunate setup, the way to escape the situation is using the exposed Java methods, such as user.entrySet(), user.get(key), etc., and not using the template language constructs like ?keys or user[key].

Google OAuth 2 authorization - Error: redirect_uri_mismatch

Make sure to check the protocol "http://" or "https://" as google checks protocol as well. Better to add both URL in the list.

How To Show And Hide Input Fields Based On Radio Button Selection

You'll need to also set the height of the element to 0 when it's hidden. I ran into this problem while using jQuery, my solution was to set the height and opacity to 0 when it's hidden, then change height to auto and opacity to 1 when it's un-hidden.

I'd recommend looking at jQuery. It's pretty easy to pick up and will allow you to do things like this a lot more easily.

$('#yesCheck').click(function() {
    $('#ifYes').slideDown();
});
$('#noCheck').click(function() {
    $('#ifYes').slideUp();
});

It's slightly better for performance to change the CSS with jQuery and use CSS3 animations to do the dropdown, but that's also more complex. The example above should work, but I haven't tested it.

How to customize the back button on ActionBar

tray this:

getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);

inside onCreate();

How do I increase the contrast of an image in Python OpenCV

Best explanation for X = aY + b (in fact it f(x) = ax + b)) is provided at https://math.stackexchange.com/a/906280/357701

A Simpler one by just adjusting lightness/luma/brightness for contrast as is below:

import cv2

img = cv2.imread('test.jpg')
cv2.imshow('test', img)
cv2.waitKey(1000)
imghsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)


imghsv[:,:,2] = [[max(pixel - 25, 0) if pixel < 190 else min(pixel + 25, 255) for pixel in row] for row in imghsv[:,:,2]]
cv2.imshow('contrast', cv2.cvtColor(imghsv, cv2.COLOR_HSV2BGR))
cv2.waitKey(1000)
raw_input()

How to make a <div> always full screen?

I don't have IE Josh, could you please test this for me. Thanks.

<html>
<head>
    <title>Hellomoto</title>
    <style text="text/javascript">
        .hellomoto
        {
            background-color:#ccc;
            position:absolute;
            top:0px;
            left:0px;
            width:100%;
            height:100%;
            overflow:auto;
        }
        body
        {
            background-color:#ff00ff;
            padding:0px;
            margin:0px;
            width:100%;
            height:100%;
            overflow:hidden;
        }
        .text
        {
            background-color:#cc00cc;
            height:800px;
            width:500px;
        }
    </style>
</head>
<body>
<div class="hellomoto">
    <div class="text">hellomoto</div>
</div>
</body>
</html>

Yes/No message box using QMessageBox

If you want to make it in python you need check this code in your workbench. also write like this. we created a popup box with python.

msgBox = QMessageBox()
msgBox.setText("The document has been modified.")
msgBox.setInformativeText("Do you want to save your changes?")
msgBox.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)
msgBox.setDefaultButton(QMessageBox.Save)
ret = msgBox.exec_()

How to attach a file using mail command on Linux?

Example using uuencode:

uuencode surfing.jpeg surfing.jpeg | mail [email protected]

and reference article:

http://www.shelldorado.com/articles/mailattachments.html

Note:

you may apt install sharutils to have uuencode command

Maintain image aspect ratio when changing height

To keep images from stretching in either axis inside a flex parent I have found a couple of solutions.

You can try using object-fit on the image which, e.g.

object-fit: contain;

http://jsfiddle.net/ykw3sfjd/

Or you can add flex-specfic rules which may work better in some cases.

align-self: center;
flex: 0 0 auto;

Get the size of a 2D array

Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:

array.length * array[0].length

DataGridView - how to set column width?

You can use the DataGridViewColumn.Width property to do it:

DataGridViewColumn column = dataGridView.Columns[0];
column.Width = 60;

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.width.aspx

how to get files from <input type='file' .../> (Indirect) with javascript

Based on Ray Nicholus's answer :

inputElement.onchange = function(event) {
   var fileList = inputElement.files;
   //TODO do something with fileList.  
}

using this will also work :

inputElement.onchange = function(event) {
   var fileList = event.target.files;
   //TODO do something with fileList.  
}

Environment variables for java installation

For deployment better to set up classpath exactly and keep environment clear. Or at *.bat (the same for linux, but with correct variables symbols):

CLASSPATH="c:\lib;d:\temp\test.jar;<long classpath>"
CLASSPATH=%CLASSPATH%;"<another_logical_droup_of_classpath" 
java -cp %CLASSPATH% com.test.MainCLass

Or at command line or *.bat (for *.sh too) if classpath id not very long:

java -cp "c:\lib;d:\temp\test.jar;<short classpath>"

Removing a model in rails (reverse of "rails g model Title...")

bundle exec rake db:rollback    
rails destroy model <model_name>

When you generate a model, it creates a database migration. If you run 'destroy' on that model, it will delete the migration file, but not the database table. So before run

bundle exec rake db:rollback

How to force input to only allow Alpha Letters?

On newer browsers, you can use:

<input type="text" name="country_code" 
    pattern="[A-Za-z]" title="Three letter country code">

You can use regular expressions to restrict the input fields.

PHP Warning Permission denied (13) on session_start()

I have had this issue before, you need more than the standard 755 or 644 permission to store the $_SESSION information. You need to be able to write to that file as that is how it remembers.

Edit a commit message in SourceTree Windows (already pushed to remote)

If the comment message includes non-English characters, using method provided by user456814, those characters will be replaced by question marks. (tested under sourcetree Ver2.5.5.0)

So I have to use the following method.

CAUTION: if the commit has been pulled by other members, changes below might cause chaos for them.

Step1: In the sourcetree main window, locate your repo tab, and click the "terminal" button to open the git command console.

Step2:

[Situation A]: target commit is the latest one.

1) In the git command console, input

git commit --amend -m "new comment message"

2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input

git push --force

[Situation B]: target commit is not the latest one.

1) In the git command console, input

git rebase -i HEAD~n

It is to squash the latest n commits. e.g. if you want to edit the message before the last one, n is 2. This command will open a vi window, the first word of each line is "pick", and you change the "pick" to "reword" for the line you want to edit. Then, input :wq to save&quit that vi window. Now, a new vi window will be open, in this window you input your new message. Also use :wq to save&quit.

2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input

git push --force


Finally: In the sourcetree main window, Press F5 to refresh.

How to delete all rows from all tables in a SQL Server database?

You could delete all the rows from all tables using an approach like Rubens suggested, or you could just drop and recreate all the tables. Always a good idea to have the full db creation scripts anyway so that may be the easiest/quickest method.

Optional query string parameters in ASP.NET Web API

if you want to pass multiple parameters then you can create model instead of passing multiple parameters.

in case you dont want to pass any parameter then you can skip as well in it, and your code will look neat and clean.

psql: could not connect to server: No such file or directory (Mac OS X)

Maybe this is unrelated but a similar error appears when you upgrade postgres to a major version using brew; using brew info postgresql found out this that helped:

To migrate existing data from a previous major version of PostgreSQL run:
brew postgresql-upgrade-database

Are querystring parameters secure in HTTPS (HTTP + SSL)?

I disagree with the advice given here - even the reference for the accepted answer concludes:

You can of course use query string parameters with HTTPS, but don’t use them for anything that could present a security problem. For example, you could safely use them to identity part numbers or types of display like ‘accountview’ or ‘printpage’, but don’t use them for passwords, credit card numbers or other pieces of information that should not be publicly available.

So, no they aren't really safe...!

rails simple_form - hidden field - create?

try this

= f.input :title, :as => :hidden, :input_html => { :value => "some value" }

How to change content on hover

This little and simple trick I just learnt may help someone trying to avoid :before or :after pseudo elements altogether (for whatever reason) in changing text on hover. You can add both texts in the HTML, but vary the CSS 'display' property based on hover. Assuming the second text 'Add' has a class named 'add-label'; here is a little modification:

span.add-label{
 display:none;
}
.item:hover span.align{
 display:none;
}
.item:hover span.add-label{
 display:block;
}

Here is a demonstration on codepen: https://codepen.io/ifekt/pen/zBaEVJ

What's your most controversial programming opinion?

The worst thing about recursion is recursion.

Using String Format to show decimal up to 2 places or simple integer

When dealing with decimals coming from a (T-)SQL database, you want to be able to convert nullable and non-nullable decimals with x decimal places and be able to review the code easily against your table definitions - and of course, display the right number of decimals to the user.

Unfortunately, the Entity Framework doesn't automatically convert something like a SQL decimal(18,2) into a .NET equivalent with the same number of decimal places (since there is only decimal with full precision available). You have to truncate the decimal places manually.

So, I did it this way:

public static class Extensions
{
    public static string ToStringDecimal(this decimal d, byte decimals)
    {
        var fmt = (decimals>0) ? "0." + new string('0', decimals) : "0";
        return d.ToString(fmt);
    }

    public static string ToStringDecimal(this decimal? d, byte decimals)
    {
        if (!d.HasValue) return "";
        return ToStringDecimal(d.Value, decimals);
    }
}

Example Usage:

void Main()
{
    decimal d = (decimal)1.2345;
    decimal? d2 = null; 

    Console.WriteLine(d.ToStringDecinal(2)); // prints: "1.23" (2 decimal places)
    Console.WriteLine(d.ToStringDecinal(0)); // prints: "1" (show integer number)
    Console.WriteLine(d2.ToStringDecimal(2)); // prints: "" (show null as empty string)
}

What does "request for member '*******' in something not a structure or union" mean?

It may also happen in the following case:

eg. if we consider the push function of a stack:

typedef struct stack
{
    int a[20];
    int head;
}stack;

void push(stack **s)
{
    int data;
    printf("Enter data:");
    scanf("%d",&(*s->a[++*s->head])); /* this is where the error is*/
}

main()
{
    stack *s;
    s=(stack *)calloc(1,sizeof(stack));
    s->head=-1;
    push(&s);
    return 0;
}

The error is in the push function and in the commented line. The pointer s has to be included within the parentheses. The correct code:

scanf("%d",&( (*s)->a[++(*s)->head]));

What does ':' (colon) do in JavaScript?

These are generally the scenarios where colon ':' is used in JavaScript

1- Declaring and Initializing an Object

var Car = {model:"2015", color:"blue"}; //car object with model and color properties

2- Setting a Label (Not recommended since it results in complicated control structure and Spaghetti code)

List: 
while(counter < 50)
{
     userInput += userInput;
     counter++;
     if(userInput > 10000)
     {
          break List;
     }
}

3- In Switch Statement

switch (new Date().getDay()) {
    case 6:
        text = "Today is Saturday";
        break; 
    case 0:
        text = "Today is Sunday";
        break; 
    default: 
        text = "Looking forward to the Weekend";
}

4- In Ternary Operator

document.getElementById("demo").innerHTML = age>18? "True" : "False";

How do I update a Python package?

Get all the outdated packages and create a batch file with the following commands pip install xxx --upgrade for each outdated packages

Read and write a String from text file

Xcode 8, Swift 3 way to read file from the app bundle:

if let path = Bundle.main.path(forResource: filename, ofType: nil) {
    do {
        let text = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
        print(text)
    } catch {
        printError("Failed to read text from \(filename)")
    }
} else {
    printError("Failed to load file from app bundle \(filename)")
} 

Here's a convenient copy and paste Extension

public extension String {
    func contentsOrBlank()->String {
        if let path = Bundle.main.path(forResource:self , ofType: nil) {
            do {
                let text = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
                return text
                } catch { print("Failed to read text from bundle file \(self)") }
        } else { print("Failed to load file from bundle \(self)") }
        return ""
    }
    }

For example

let t = "yourFile.txt".contentsOrBlank()

You almost always want an array of lines:

let r:[String] = "yourFile.txt"
     .contentsOrBlank()
     .characters
     .split(separator: "\n", omittingEmptySubsequences:ignore)
     .map(String.init)

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

My solution is a bit funny.I never thought that would it be as easy as save as with UTF-8 codec.I'm using notepad++(v5.6.8).I didn't notice that I saved it with ANSI codec initially. I'm using separate file to place all localized dictionary. I found my solution under 'Encoding' tab from my Notepad++.I select 'Encoding in UTF-8 without BOM' and save it. It works brilliantly.

DISABLE the Horizontal Scroll

this is the nasty child of your code :)

.container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container {
width: 1170px;
}

replace it with

.container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container {
width: 100%;
}

Getting "type or namespace name could not be found" but everything seems ok?

You might also try eliminating the code you think you're having problems with and seeing if it compiles with no references to that code. If not, fix things until it compiles again, and then work your suspected problem code back in. Sometimes I get strange errors about classes or methods that I know are correct when the compiler doesn't like something else. Once I fix the thing that it's really getting hung up on, these 'phantom' errors disappear.

Rotate label text in seaborn factorplot

Aman is correct that you can use normal matplotlib commands, but this is also built into the FacetGrid:

import seaborn as sns
planets = sns.load_dataset("planets")
g = sns.factorplot("year", data=planets, aspect=1.5, kind="count", color="b")
g.set_xticklabels(rotation=30)

enter image description here

There are some comments and another answer claiming this "doesn't work", however, anyone can run the code as written here and see that it does work. The other answer does not provide a reproducible example of what isn't working, making it very difficult to address, but my guess is that people are trying to apply this solution to the output of functions that return an Axes object instead of a Facet Grid. These are different things, and the Axes.set_xticklabels() method does indeed require a list of labels and cannot simply change the properties of the existing labels on the Axes. The lesson is that it's important to pay attention to what kind of objects you are working with.

how to change php version in htaccess in server

To switch to PHP 4.4:

AddHandler application/x-httpd-php4 .php .php4 .php3

To switch to PHP 5.0:

AddHandler application/x-httpd-php5 .php .php5 .php4 .php3

To switch to PHP 5.1:

AddHandler application/x-httpd-php51 .php .php5 .php4 .php3

To switch to PHP 5.2:

AddHandler application/x-httpd-php52 .php .php5 .php4 .php3

To switch to PHP 5.3:

AddHandler application/x-httpd-php53 .php .php5 .php4 .php3

To switch to PHP 5.4:

AddHandler application/x-httpd-php54 .php .php5 .php4 .php3

To switch to PHP 5.5:

AddHandler application/x-httpd-php55 .php .php5 .php4 .php3

To switch to the secure PHP 5.2 with Suhosin patch:

AddHandler application/x-httpd-php52s .php .php5 .php4 .php3

what is the difference between const_iterator and iterator?

Performance wise there is no difference. The only purpose of having const_iterator over iterator is to manage the accessesibility of the container on which the respective iterator runs. You can understand it more clearly with an example:

std::vector<int> integers{ 3, 4, 56, 6, 778 };

If we were to read & write the members of a container we will use iterator:

for( std::vector<int>::iterator it = integers.begin() ; it != integers.end() ; ++it )
       {*it = 4;  std::cout << *it << std::endl; }

If we were to only read the members of the container integers you might wanna use const_iterator which doesn't allow to write or modify members of container.

for( std::vector<int>::const_iterator it = integers.begin() ; it != integers.end() ; ++it )
       { cout << *it << endl; }

NOTE: if you try to modify the content using *it in second case you will get an error because its read-only.

select from one table, insert into another table oracle sql query

From the oracle documentation, the below query explains it better

INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;

You can read this link

Your query would be as follows

//just the concept    
    INSERT INTO quotedb
    (COLUMN_NAMES) //seperated by comma
    SELECT COLUMN_NAMES FROM tickerdb,quotedb WHERE quotedb.ticker = tickerdb.ticker

Note: Make sure the columns in insert and select are in right position as per your requirement

Hope this helps!

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

Plain JavaScript:

You don't need jQuery to do something trivial like this. Just use the .removeAttribute() method.

Assuming you are just targeting a single element, you can easily use the following: (example)

document.querySelector('#target').removeAttribute('style');

If you are targeting multiple elements, just loop through the selected collection of elements: (example)

var target = document.querySelectorAll('div');
Array.prototype.forEach.call(target, function(element){
    element.removeAttribute('style');
});

Array.prototype.forEach() - IE9 and above / .querySelectorAll() - IE 8 (partial) IE9 and above.