Programs & Examples On #Stunnel

WebSockets and Apache proxy : how to configure mod_proxy_wstunnel?

TODO:

  1. Have Apache 2.4 installed (doesn't work with 2.2), a2enmod proxy and a2enmod proxy_wstunnel.load

  2. Do this in the Apache config
    just add two line in your file where 8080 is your tomcat running port

    <VirtualHost *:80>
    ProxyPass "/ws2/" "ws://localhost:8080/" 
    ProxyPass "/wss2/" "wss://localhost:8080/"
    
    </VirtualHost *:80>
    

Apache Proxy: No protocol handler was valid

In my case, I needed proxy_ajp module.

a2enmod proxy proxy_http proxy_ajp 

OpenSSL: PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: TRUSTED CERTIFICATE

My situation was a little different. The solution was to strip the .pem from everything outside of the CERTIFICATE and PRIVATE KEY sections and to invert the order which they appeared. After converting from pfx to pem file, the certificate looked like this:

Bag Attributes
localKeyID: ...
issuer=...
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
Bag Attributes
more garbage...
-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----

After correcting the file, it was just:

-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----

Reportviewer tool missing in visual studio 2017 RC

If you're like me and tried a few of these methods and are stuck at the point that you have the control in the toolbox and can draw it on the form but it disappears from the form and puts it down in the components, then simply edit the designer and add the following in the appropriate area of InitializeComponent() to make it visible:

this.Controls.Add(this.reportViewer1);

or

[ContainerControl].Controls.Add(this.reportViewer1);

You'll also need to make adjustments to the location and size manually after you've added the control.

Not a great answer for sure, but if you're stuck and just need to get work done for now until you have more time to figure it out, it should help.

How to get a DOM Element from a JQuery Selector

If you need to interact directly with the DOM element, why not just use document.getElementById since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.

But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.

UPDATE: Based on a comment: Here is a post with a nice explanation: http://www.mail-archive.com/[email protected]/msg04461.html

$(this).attr("checked") ? $(this).val() : 0

This will return the value if it's checked, or 0 if it's not.

$(this).val() is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.

How to get a password from a shell script without echoing

The -s option of read is not defined in the POSIX standard. See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/read.html. I wanted something that would work for any POSIX shell, so I wrote a little function that uses stty to disable echo.

#!/bin/sh

# Read secret string
read_secret()
{
    # Disable echo.
    stty -echo

    # Set up trap to ensure echo is enabled before exiting if the script
    # is terminated while echo is disabled.
    trap 'stty echo' EXIT

    # Read secret.
    read "$@"

    # Enable echo.
    stty echo
    trap - EXIT

    # Print a newline because the newline entered by the user after
    # entering the passcode is not echoed. This ensures that the
    # next line of output begins at a new line.
    echo
}

This function behaves quite similar to the read command. Here is a simple usage of read followed by similar usage of read_secret. The input to read_secret appears empty because it was not echoed to the terminal.

[susam@cube ~]$ read a b c
foo \bar baz \qux
[susam@cube ~]$ echo a=$a b=$b c=$c
a=foo b=bar c=baz qux
[susam@cube ~]$ unset a b c
[susam@cube ~]$ read_secret a b c

[susam@cube ~]$ echo a=$a b=$b c=$c
a=foo b=bar c=baz qux
[susam@cube ~]$ unset a b c

Here is another that uses the -r option to preserve the backslashes in the input. This works because the read_secret function defined above passes all arguments it receives to the read command.

[susam@cube ~]$ read -r a b c
foo \bar baz \qux
[susam@cube ~]$ echo a=$a b=$b c=$c
a=foo b=\bar c=baz \qux
[susam@cube ~]$ unset a b c
[susam@cube ~]$ read_secret -r a b c

[susam@cube ~]$ echo a=$a b=$b c=$c
a=foo b=\bar c=baz \qux
[susam@cube ~]$ unset a b c

Finally, here is an example that shows how to use the read_secret function to read a password in a POSIX compliant manner.

printf "Password: "
read_secret password
# Do something with $password here ...

how to activate a textbox if I select an other option in drop down box

Below is the core JavaScript you need to write:

<html> 
<head>  
<script type="text/javascript">
function CheckColors(val){
 var element=document.getElementById('color');
 if(val=='pick a color'||val=='others')
   element.style.display='block';
 else  
   element.style.display='none';
}

</script> 
</head>
<body>
  <select name="color" onchange='CheckColors(this.value);'> 
    <option>pick a color</option>  
    <option value="red">RED</option>
    <option value="blue">BLUE</option>
    <option value="others">others</option>
  </select>
<input type="text" name="color" id="color" style='display:none;'/>
</body>
</html>

Richtextbox wpf binding

 <RichTextBox>
     <FlowDocument PageHeight="180">
         <Paragraph>
             <Run Text="{Binding Text, Mode=TwoWay}"/>
          </Paragraph>
     </FlowDocument>
 </RichTextBox>

This seems to be the easiest way by far and isn't displayed in any of these answers.

In the view model just have the Text variable.

python: order a list of numbers without built-in sort, min, max function

I guess you are trying to do something like this:

data_list = [-5, -23, 5, 0, 23, -6, 23, 67]
new_list = []

while data_list:
    minimum = data_list[0]  # arbitrary number in list 
    for x in data_list: 
        if x < minimum:
            minimum = x
    new_list.append(minimum)
    data_list.remove(minimum)    

print new_list

Node.js fs.readdir recursive directory search

If you want to use an npm package, wrench is pretty good.

var wrench = require("wrench");

var files = wrench.readdirSyncRecursive("directory");

wrench.readdirRecursive("directory", function (error, files) {
    // live your dreams
});

EDIT (2018):
Anyone reading through in recent time: The author deprecated this package in 2015:

wrench.js is deprecated, and hasn't been updated in quite some time. I heavily recommend using fs-extra to do any extra filesystem operations.

Python: Finding differences between elements of a list

In the upcoming Python 3.10 release schedule, with the new pairwise function it's possible to slide through pairs of elements and thus map on rolling pairs:

from itertools import pairwise

[y-x for (x, y) in pairwise([1, 3, 6, 7])]
# [2, 3, 1]

The intermediate result being:

pairwise([1, 3, 6, 7])
# [(1, 3), (3, 6), (6, 7)]

Convert UIImage to NSData and convert back to UIImage in Swift?

Thanks. Helped me a lot. Converted to Swift 3 and worked

To save: let data = UIImagePNGRepresentation(image)

To load: let image = UIImage(data: data)

How can I stop Chrome from going into debug mode?

I have made it working...

Please follow the highlighted mark in the attached image.

Enter image description here

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

Your Customer class has to be discovered by CDI as a bean. For that you have two options:

  1. Put a bean defining annotation on it. As @Model is a stereotype it's why it does the trick. A qualifier like @Named is not a bean defining annotation, reason why it doesn't work

  2. Change the bean discovery mode in your bean archive from the default "annotated" to "all" by adding a beans.xml file in your jar.

Keep in mind that @Named has only one usage : expose your bean to the UI. Other usages are for bad practice or compatibility with legacy framework.

How can I copy a file on Unix using C?

There is no need to either call non-portable APIs like sendfile, or shell out to external utilities. The same method that worked back in the 70s still works now:

#include <fcntl.h>
#include <unistd.h>
#include <errno.h>

int cp(const char *to, const char *from)
{
    int fd_to, fd_from;
    char buf[4096];
    ssize_t nread;
    int saved_errno;

    fd_from = open(from, O_RDONLY);
    if (fd_from < 0)
        return -1;

    fd_to = open(to, O_WRONLY | O_CREAT | O_EXCL, 0666);
    if (fd_to < 0)
        goto out_error;

    while (nread = read(fd_from, buf, sizeof buf), nread > 0)
    {
        char *out_ptr = buf;
        ssize_t nwritten;

        do {
            nwritten = write(fd_to, out_ptr, nread);

            if (nwritten >= 0)
            {
                nread -= nwritten;
                out_ptr += nwritten;
            }
            else if (errno != EINTR)
            {
                goto out_error;
            }
        } while (nread > 0);
    }

    if (nread == 0)
    {
        if (close(fd_to) < 0)
        {
            fd_to = -1;
            goto out_error;
        }
        close(fd_from);

        /* Success! */
        return 0;
    }

  out_error:
    saved_errno = errno;

    close(fd_from);
    if (fd_to >= 0)
        close(fd_to);

    errno = saved_errno;
    return -1;
}

gdb fails with "Unable to find Mach task port for process-id" error

The problem is that you are not logged in as a root user (which you don't want). You need to create a certificate for gdb to be allowed access. Follow this tutorial and you should be good to go...

http://sourceware.org/gdb/wiki/BuildingOnDarwin

If all else fails, just use: sudo gdb executableFileName

MySQL select query with multiple conditions

You have conditions that are mutually exclusive - if meta_key is 'first_name', it can't also be 'yearofpassing'. Most likely you need your AND's to be OR's:

$result = mysql_query("SELECT user_id FROM wp_usermeta 
WHERE (meta_key = 'first_name' AND meta_value = '$us_name') 
OR (meta_key = 'yearofpassing' AND meta_value = '$us_yearselect') 
OR (meta_key = 'u_city' AND meta_value = '$us_reg') 
OR (meta_key = 'us_course' AND meta_value = '$us_course')")

How to concatenate strings in twig

In Symfony you can use this for protocol and host:

{{ app.request.schemeAndHttpHost }}

Though @alessandro1997 gave a perfect answer about concatenation.

How to get the url parameters using AngularJS

Simple and easist way to get url value

First add # to url (e:g -  test.html#key=value)

url in browser (https://stackover.....king-angularjs-1-5#?brand=stackoverflow)

var url = window.location.href 

(output: url = "https://stackover.....king-angularjs-1-5#?brand=stackoverflow")

url.split('=').pop()
output "stackoverflow"

What's the difference between process.cwd() vs __dirname?

As per node js doc process.cwd()

cwd is a method of global object process, returns a string value which is the current working directory of the Node.js process.

As per node js doc __dirname

The directory name of current script as a string value. __dirname is not actually a global but rather local to each module.

Let me explain with example,

suppose we have a main.js file resides inside C:/Project/main.js and running node main.js both these values return same file

or simply with following folder structure

Project 
+-- main.js
+--lib
   +-- script.js

main.js

console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true

suppose we have another file script.js files inside a sub directory of project ie C:/Project/lib/script.js and running node main.js which require script.js

main.js

require('./lib/script.js')
console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true

script.js

console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project\lib
console.log(__dirname===process.cwd())
// false

What is the correct Performance Counter to get CPU and Memory Usage of a Process?

From this post:

To get the entire PC CPU and Memory usage:

using System.Diagnostics;

Then declare globally:

private PerformanceCounter theCPUCounter = 
   new PerformanceCounter("Processor", "% Processor Time", "_Total"); 

Then to get the CPU time, simply call the NextValue() method:

this.theCPUCounter.NextValue();

This will get you the CPU usage

As for memory usage, same thing applies I believe:

private PerformanceCounter theMemCounter = 
   new PerformanceCounter("Memory", "Available MBytes");

Then to get the memory usage, simply call the NextValue() method:

this.theMemCounter.NextValue();

For a specific process CPU and Memory usage:

private PerformanceCounter theCPUCounter = 
   new PerformanceCounter("Process", "% Processor Time",              
   Process.GetCurrentProcess().ProcessName);

where Process.GetCurrentProcess().ProcessName is the process name you wish to get the information about.

private PerformanceCounter theMemCounter = 
   new PerformanceCounter("Process", "Working Set",
   Process.GetCurrentProcess().ProcessName);

where Process.GetCurrentProcess().ProcessName is the process name you wish to get the information about.

Note that Working Set may not be sufficient in its own right to determine the process' memory footprint -- see What is private bytes, virtual bytes, working set?

To retrieve all Categories, see Walkthrough: Retrieving Categories and Counters

The difference between Processor\% Processor Time and Process\% Processor Time is Processor is from the PC itself and Process is per individual process. So the processor time of the processor would be usage on the PC. Processor time of a process would be the specified processes usage. For full description of category names: Performance Monitor Counters

An alternative to using the Performance Counter

Use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.

Change mysql user password using command line

Your login root should be /usr/local/directadmin/conf/mysql.conf. Then try following

UPDATE mysql.user SET password=PASSWORD('$w0rdf1sh') WHERE user='tate256' AND Host='10.10.2.30';
FLUSH PRIVILEGES;

Host is your mysql host.

How to avoid .pyc files?

You could make the directories that your modules exist in read-only for the user that the Python interpreter is running as.

I don't think there's a more elegant option. PEP 304 appears to have been an attempt to introduce a simple option for this, but it appears to have been abandoned.

I imagine there's probably some other problem you're trying to solve, for which disabling .py[co] would appear to be a workaround, but it'll probably be better to attack whatever this original problem is instead.

Dynamically creating keys in a JavaScript associative array

In response to MK_Dev, one is able to iterate, but not consecutively (for that, obviously an array is needed).

A quick Google search brings up hash tables in JavaScript.

Example code for looping over values in a hash (from the aforementioned link):

var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;

// Show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}

-bash: syntax error near unexpected token `newline'

The characters '<', and '>', are to indicate a place-holder, you should remove them to read:

php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME

Excel VBA Run-time error '13' Type mismatch

Diogo

Justin has given you some very fine tips :)

You will also get that error if the cell where you are performing the calculation has an error resulting from a formula.

For example if Cell A1 has #DIV/0! error then you will get "Excel VBA Run-time error '13' Type mismatch" when performing this code

Sheets("Sheet1").Range("A1").Value - 1

I have made some slight changes to your code. Could you please test it for me? Copy the code with the line numbers as I have deliberately put them there.

Option Explicit

Sub Sample()
  Dim ws As Worksheet
  Dim x As Integer, i As Integer, a As Integer, y As Integer
  Dim name As String
  Dim lastRow As Long
10        On Error GoTo Whoa

20        Application.ScreenUpdating = False

30        name = InputBox("Please insert the name of the sheet")

40        If Len(Trim(name)) = 0 Then Exit Sub

50        Set ws = Sheets(name)

60        With ws
70            If Not IsError(.Range("BE4").Value) Then
80                x = Val(.Range("BE4").Value)
90            Else
100               MsgBox "Please check the value of cell BE4. It seems to have an error"
110               GoTo LetsContinue
120           End If

130           .Range("BF4").Value = x

140           lastRow = .Range("BE" & Rows.Count).End(xlUp).Row

150           For i = 5 To lastRow
160               If IsError(.Range("BE" & i)) Then
170                   MsgBox "Please check the value of cell BE" & i & ". It seems to have an error"
180                   GoTo LetsContinue
190               End If

200               a = 0: y = Val(.Range("BE" & i))
210               If y <> x Then
220                   If y <> 0 Then
230                       If y = 3 Then
240                           a = x
250                           .Range("BF" & i) = Val(.Range("BE" & i)) - x

260                           x = Val(.Range("BE" & i)) - x
270                       End If
280                       .Range("BF" & i) = Val(.Range("BE" & i)) - a
290                       x = Val(.Range("BE" & i)) - a
300                   Else
310                       .Range("BF" & i).ClearContents
320                   End If
330               Else
340                   .Range("BF" & i).ClearContents
350               End If
360           Next i
370       End With

LetsContinue:
380       Application.ScreenUpdating = True
390       Exit Sub
Whoa:
400       MsgBox "Error Description :" & Err.Description & vbNewLine & _
         "Error at line     : " & Erl
410       Resume LetsContinue
End Sub

Ruby combining an array into one string

While a bit more cryptic than join, you can also multiply the array by a string.

@arr * " "

Why can I not push_back a unique_ptr into a vector?

std::unique_ptr has no copy constructor. You create an instance and then ask the std::vector to copy that instance during initialisation.

error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::uniqu
e_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_D
eleter = std::default_delete<int>, std::unique_ptr<_Tp, _Tp_Deleter> =
 std::unique_ptr<int>]'

The class satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable.

The following works with the new emplace calls.

std::vector< std::unique_ptr< int > > vec;
vec.emplace_back( new int( 1984 ) );

See using unique_ptr with standard library containers for further reading.

Double decimal formatting in Java

With Java 8, you can use format method..: -

System.out.format("%.2f", 4.0); // OR

System.out.printf("%.2f", 4.0); 
  • f is used for floating point value..
  • 2 after decimal denotes, number of decimal places after .

For most Java versions, you can use DecimalFormat: -

    DecimalFormat formatter = new DecimalFormat("#0.00");
    double d = 4.0;
    System.out.println(formatter.format(d));

C# Telnet Library

I ended up finding MinimalistTelnet and adapted it to my uses. I ended up needing to be able to heavily modify the code due to the unique** device that I am attempting to attach to.

** Unique in this instance can be validly interpreted as brain-dead.

Setting table column width

Add colgroup after your table tag. Define width and number of column here. and add tbody tag. Put your tr inside of tbody.

<table>
    <colgroup>
       <col span="1" style="width: 30%;">
       <col span="1" style="width: 70%;">
    </colgroup>


    <tbody>
        <tr>
            <td>First column</td>
            <td>Second column</td>
        </tr>
    </tbody>
</table>

How to resize image automatically on browser width resize but keep same height?

Since you are having trouble adjusting the height you might be able to use this. http://jsfiddle.net/uf9bx/1/

img{
width: 100%;
height: 100%;
max-height: 300px;
}

I'm not sure exactly what size or location you are putting your images but maybe this will help!

How do I convert a float number to a whole number in JavaScript?

Note: You cannot use Math.floor() as a replacement for truncate, because Math.floor(-3.1) = -4 and not -3 !!

A correct replacement for truncate would be:

function truncate(value)
{
    if (value < 0) {
        return Math.ceil(value);
    }

    return Math.floor(value);
}

Counter in foreach loop in C#

Your understanding of foreach is incomplete.

It works with any type that exposes IEnumerable (or implements a GetEnumerable method) and uses the returned IEnumerator to iterate over the items in the collection.

How the Enumerator does this (using an index, yield statement or magic) is an implementation detail.

In order to achieve what you want, you should use a for loop:

for (int i = 0; i < mylist.Count; i++)
{
}

Note:

Getting the number of items in a list is slightly different depending on the type of list

For Collections: Use Count   [property]
For Arrays:      Use Length  [property]
For IEnumerable: Use Count() [Linq method]

how to create a cookie and add to http response from inside my service layer?

To add a new cookie, use HttpServletResponse.addCookie(Cookie). The Cookie is pretty much a key value pair taking a name and value as strings on construction.

How to use hex() without 0x in Python?

Use this code:

'{:x}'.format(int(line))

it allows you to specify a number of digits too:

'{:06x}'.format(123)
# '00007b'

For Python 2.6 use

'{0:x}'.format(int(line))

or

'{0:06x}'.format(int(line))

How to draw in JPanel? (Swing/graphics Java)

Here is a simple example. I suppose it will be easy to understand:

import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Graph extends JFrame {
JFrame f = new JFrame();
JPanel jp;


public Graph() {
    f.setTitle("Simple Drawing");
    f.setSize(300, 300);
    f.setDefaultCloseOperation(EXIT_ON_CLOSE);

    jp = new GPanel();
    f.add(jp);
    f.setVisible(true);
}

public static void main(String[] args) {
    Graph g1 = new Graph();
    g1.setVisible(true);
}

class GPanel extends JPanel {
    public GPanel() {
        f.setPreferredSize(new Dimension(300, 300));
    }

    @Override
    public void paintComponent(Graphics g) {
        //rectangle originates at 10,10 and ends at 240,240
        g.drawRect(10, 10, 240, 240);
        //filled Rectangle with rounded corners.    
        g.fillRoundRect(50, 50, 100, 100, 80, 80);
    }
}

}

And the output looks like this:

Output

Using ORDER BY and GROUP BY together

SQL>

SELECT interview.qtrcode QTR, interview.companyname "Company Name", interview.division Division 
FROM interview 
JOIN jobsdev.employer 
    ON (interview.companyname = employer.companyname AND employer.zipcode like '100%')
GROUP BY interview.qtrcode, interview.companyname, interview.division
ORDER BY interview.qtrcode;

How do I use jQuery to redirect?

You forgot the HTTP part:

window.location.href = "http://example.com/Registration/Success/";

lexers vs parsers

There are a number of reasons why the analysis portion of a compiler is normally separated into lexical analysis and parsing ( syntax analysis) phases.

  1. Simplicity of design is the most important consideration. The separation of lexical and syntactic analysis often allows us to simplify at least one of these tasks. For example, a parser that had to deal with comments and white space as syntactic units would be. Considerably more complex than one that can assume comments and white space have already been removed by the lexical analyzer. If we are designing a new language, separating lexical and syntactic concerns can lead to a cleaner overall language design.
  2. Compiler efficiency is improved. A separate lexical analyzer allows us to apply specialized techniques that serve only the lexical task, not the job of parsing. In addition, specialized buffering techniques for reading input characters can speed up the compiler significantly.
  3. Compiler portability is enhanced. Input-device-specific peculiarities can be restricted to the lexical analyzer.

resource___Compilers (2nd Edition) written by- Alfred V. Abo Columbia University Monica S. Lam Stanford University Ravi Sethi Avaya Jeffrey D. Ullman Stanford University

How to insert a line break <br> in markdown

Try adding 2 spaces (or a backslash \) after the first line:

[Name of link](url)
My line of text\

Visually:

[Name of link](url)<space><space>
My line of text\

Output:

<p><a href="url">Name of link</a><br>
My line of text<br></p>

How to convert a HTMLElement to a string

I was using Angular, and needed the same thing, and landed at this post.

@ViewChild('myHTML', {static: false}) _html: ElementRef;
this._html.nativeElement;

Convert string to ASCII value python

your description is rather confusing; directly concatenating the decimal values doesn't seem useful in most contexts. the following code will cast each letter to an 8-bit character, and THEN concatenate. this is how standard ASCII encoding works

def ASCII(s):
    x = 0
    for i in xrange(len(s)):
        x += ord(s[i])*2**(8 * (len(s) - i - 1))
    return x

How do I disable a jquery-ui draggable?

Could create a DisableDrag(myObject) and a EnableDrag(myObject) function

myObject.draggable( 'disable' )

Then

myObject.draggable( 'enable' )

Break statement in javascript array map method

That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] < 10) {
    hasValueLessThanTen = true;
    break;
  }
}

Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

var hasValueLessThanTen = myArray.some(function (val) { 
  return val < 10;
});

Purge Kafka Topic

While the accepted answer is correct, that method has been deprecated. Topic configuration should now be done via kafka-configs.

kafka-configs --zookeeper localhost:2181 --entity-type topics --alter --add-config retention.ms=1000 --entity-name MyTopic

Configurations set via this method can be displayed with the command

kafka-configs --zookeeper localhost:2181 --entity-type topics --describe --entity-name MyTopic

How to fetch the dropdown values from database and display in jsp

  1. Make the database connection and retrieve the query result.
  2. Traverse through the result and display the query results.

The example code below demonstrates this in detail.

<%@page import="java.sql.*, java.io.*,listresult"%> //import the required library

<%

String label = request.getParameter("label"); // retrieving a variable from a previous page

Connection dbc = null; //Make connection to the database
Class.forName("com.mysql.jdbc.Driver");
dbc = DriverManager.getConnection("jdbc:mysql://localhost:3306/works", "root", "root");
if (dbc != null) 
{
    System.out.println("Connection successful");
}

ResultSet rs = listresult.dbresult.func(dbc, label); //This function is in the end. The function is defined in another package- listresult

%>

<form name="demo form" method="post">

    <table>
        <tr>
            <td>
                Label Name:
            </td>

            <td>
                <input type="text" name="label" value="<%=rs.getString("labelname")%>">
            </td>

            <td>
                <select name="label">
                <option value="">SELECT</option>

                <% while (rs.next()) {%>

                    <option value="<%=rs.getString("lname")%>"><%=rs.getString("lname")%>
                    </option>

                <%}%>
                </select>
            </td>
        </tr>
    </table>

</form>

//The function:

public static ResultSet func(Connection dbc, String x)
{
    ResultSet rs = null;
    String sql;
    PreparedStatement pst;
    try
    {
        sql = "select lname from demo where label like '" + x + "'";
        pst = dbc.prepareStatement(sql);
        rs = pst.executeQuery();
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
        String sqlMessage = e.getMessage();
    }
    return rs;
}

I have tried to make this example as detailed as possible. Do ask if you have any queries.

Redirecting to a certain route based on condition

It's possible to redirect to another view with angular-ui-router. For this purpose, we have the method $state.go("target_view"). For example:

 ---- app.js -----

 var app = angular.module('myApp', ['ui.router']);

 app.config(function ($stateProvider, $urlRouterProvider) {

    // Otherwise
    $urlRouterProvider.otherwise("/");

    $stateProvider
            // Index will decide if redirects to Login or Dashboard view
            .state("index", {
                 url: ""
                 controller: 'index_controller'
              })
            .state('dashboard', {
                url: "/dashboard",
                controller: 'dashboard_controller',
                templateUrl: "views/dashboard.html"
              })
            .state('login', {
                url: "/login",
                controller: 'login_controller',
                templateUrl: "views/login.html"
              });
 });

 // Associate the $state variable with $rootScope in order to use it with any controller
 app.run(function ($rootScope, $state, $stateParams) {
        $rootScope.$state = $state;
        $rootScope.$stateParams = $stateParams;
    });

 app.controller('index_controller', function ($scope, $log) {

    /* Check if the user is logged prior to use the next code */

    if (!isLoggedUser) {
        $log.log("user not logged, redirecting to Login view");
        // Redirect to Login view 
        $scope.$state.go("login");
    } else {
        // Redirect to dashboard view 
        $scope.$state.go("dashboard");
    }

 });

----- HTML -----

<!DOCTYPE html>
<html>
    <head>
        <title>My WebSite</title>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="description" content="MyContent">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <script src="js/libs/angular.min.js" type="text/javascript"></script>
        <script src="js/libs/angular-ui-router.min.js" type="text/javascript"></script>
        <script src="js/app.js" type="text/javascript"></script>

    </head>
    <body ng-app="myApp">
        <div ui-view></div>
    </body>
</html>

Change IPython/Jupyter notebook working directory

For linux and Windows: Just modify 1 line, and you can change it.

1. Open file

cwp.py

in

C:\Users\ [your computer name]\Anaconda2

.

2. find the line 

os.chdir(documents_folder)

at the end of the file.

Change it to

os.chdir("your expected working folder")

for example: os.chdir("D:/Jupyter_folder")

3. save and close.

It worked.


Update:

When it comes to MacOS, I couldn't find the cwp.py. Here is what I found:

Open terminal on your Macbook, run 'jupyter notebook --generate-config'.

It will create a config file at /Users/[your_username]/.jupyter/jupyter_notebook_config.py

Open the config file, then change this line #c.NotebookApp.notebook_dir = '' to c.NotebookApp.notebook_dir = 'your path' and remember un-comment this line too.

For example, I change my path to '/Users/catbuilts/JupyterProjects/'

Running a cron job on Linux every six hours

0 */6 * * *

crontab every 6 hours is a commonly used cron schedule.

AJAX jQuery refresh div every 5 seconds

Try this out.

function loadlink(){
    $('#links').load('test.php',function () {
         $(this).unwrap();
    });
}

loadlink(); // This will run on page load
setInterval(function(){
    loadlink() // this will run after every 5 seconds
}, 5000);

Hope this helps.

Confused about Service vs Factory

For short and simple explanation refer https://stackoverflow.com/a/26924234/5811973.

For detailed explanation refer https://stackoverflow.com/a/15666049/5811973.

Also from angularJs documentation: enter image description here

Two decimal places using printf( )

For %d part refer to this How does this program work? and for decimal places use %.2f

How do I install a custom font on an HTML site

Yes, you can use the CSS feature named @font-face. It has only been officially approved in CSS3, but been proposed and implemented in CSS2 and has been supported in IE for quite a long time.

You declare it in the CSS like this:

 @font-face { font-family: Delicious; src: url('Delicious-Roman.otf'); } 
 @font-face { font-family: Delicious; font-weight: bold; src: url('Delicious-Bold.otf');}

Then, you can just reference it like the other standard fonts:

 h3 { font-family: Delicious, sans-serif; }

So, in this case,

<html>
   <head>
    <style>
      @font-face { font-family: JuneBug; src: url('JUNEBUG.TTF'); } 
      h1 {
         font-family: JuneBug
      }
    </style>
   </head>
   <body>
      <h1>Hey, June</h1>
   </body>
</html>

And you just need to put the JUNEBUG.TFF in the same location as the html file.

I downloaded the font from the dafont.com website:

http://www.dafont.com/junebug.font

Javascript Regex: How to put a variable inside a regular expression?

if you're using es6 template literals are an option...

string.replace(new RegExp(`ReGeX${testVar}ReGeX`), "replacement")

Fatal error: Call to undefined function mysql_connect()

I had this same problem on RHEL6. It turns out that the mysql.ini file in /etc/php.d only had a module name but needed a full path name. On my RHEL6 system the entry that works is:

; Enable mysql extension module

extension=/usr/lib64/php/modules/mysql.so

After modifying the file, I restarted apache and everything worked.

fstream won't create a file

You need to add some arguments. Also, instancing and opening can be put in one line:

fstream file("test.txt", fstream::in | fstream::out | fstream::trunc);

Best way to run scheduled tasks

Additionally, if your application uses SQL SERVER you can use the SQL Agent to schedule your tasks. This is where we commonly put re-occurring code that is data driven (email reminders, scheduled maintenance, purges, etc...). A great feature that is built in with the SQL Agent is failure notification options, which can alert you if a critical task fails.

Is there an onSelect event or equivalent for HTML <select>?

The wonderful thing about the select tag (in this scenario) is that it will grab its value from the option tags.

Try:

<select onChange="javascript:doSomething(this.value);">
<option value="A">A</option>
<option value="B">B</option>
<option value="Foo">C</option>
</select>

Worked decent for me.

docker cannot start on windows

I run in to the same problem. I solved this by enabling hyper-v.

  1. Enable virtualization in BIOS
  2. Install hyper-v

PuTTY Connection Manager download?

PuTTY Session Manager is a tool that allows system administrators to organise their PuTTY sessions into folders and assign hotkeys to favourite sessions. Multiple sessions can be launched with one click. Requires MS Windows and the .NET 2.0 Runtime.

http://sourceforge.net/projects/puttysm/

PHP Composer behind http proxy

Try this:

export HTTPS_PROXY_REQUEST_FULLURI=false

solved this issue for me working behind a proxy at a company few weeks ago.

Calculate correlation with cor(), only for numerical columns

if you have a dataframe where some columns are numeric and some are other (character or factor) and you only want to do the correlations for the numeric columns, you could do the following:

set.seed(10)

x = as.data.frame(matrix(rnorm(100), ncol = 10))
x$L1 = letters[1:10]
x$L2 = letters[11:20]

cor(x)

Error in cor(x) : 'x' must be numeric

but

cor(x[sapply(x, is.numeric)])

             V1         V2          V3          V4          V5          V6          V7
V1   1.00000000  0.3025766 -0.22473884 -0.72468776  0.18890578  0.14466161  0.05325308
V2   0.30257657  1.0000000 -0.27871430 -0.29075170  0.16095258  0.10538468 -0.15008158
V3  -0.22473884 -0.2787143  1.00000000 -0.22644156  0.07276013 -0.35725182 -0.05859479
V4  -0.72468776 -0.2907517 -0.22644156  1.00000000 -0.19305921  0.16948333 -0.01025698
V5   0.18890578  0.1609526  0.07276013 -0.19305921  1.00000000  0.07339531 -0.31837954
V6   0.14466161  0.1053847 -0.35725182  0.16948333  0.07339531  1.00000000  0.02514081
V7   0.05325308 -0.1500816 -0.05859479 -0.01025698 -0.31837954  0.02514081  1.00000000
V8   0.44705527  0.1698571  0.39970105 -0.42461411  0.63951574  0.23065830 -0.28967977
V9   0.21006372 -0.4418132 -0.18623823 -0.25272860  0.15921890  0.36182579 -0.18437981
V10  0.02326108  0.4618036 -0.25205899 -0.05117037  0.02408278  0.47630138 -0.38592733
              V8           V9         V10
V1   0.447055266  0.210063724  0.02326108
V2   0.169857120 -0.441813231  0.46180357
V3   0.399701054 -0.186238233 -0.25205899
V4  -0.424614107 -0.252728595 -0.05117037
V5   0.639515737  0.159218895  0.02408278
V6   0.230658298  0.361825786  0.47630138
V7  -0.289679766 -0.184379813 -0.38592733
V8   1.000000000  0.001023392  0.11436143
V9   0.001023392  1.000000000  0.15301699
V10  0.114361431  0.153016985  1.00000000

How to stop tracking and ignore changes to a file in Git?

Lots of people advise you to use git update-index --assume-unchanged. Indeed, this may be a good solution, but only in the short run.

What you probably want to do is this: git update-index --skip-worktree.

(The third option, which you probably don't want is: git rm --cached. It will keep your local file, but will be marked as removed from the remote repository.)

Difference between the first two options?

  • assume-unchanged is to temporary allow you to hide modifications from a file. If you want to hide modifications done to a file, modify the file, then checkout another branch, you'll have to use no-assume-unchanged then probably stash modifications done.
  • skip-worktree will follow you whatever the branch you checkout, with your modifications!

Use case of assume-unchanged

It assumes this file should not be modified, and gives you a cleaner output when doing git status. But when checking out to another branch, you need to reset the flag and commit or stash changes before so. If you pull with this option activated, you'll need to solve conflicts and git won't auto merge. It actually only hides modifications (git status won't show you the flagged files).

I like to use it when I only want to stop tracking changes for a while + commit a bunch of files (git commit -a) related to the same modification.

Use case of skip-worktree

You have a setup class containing parameters (eg. including passwords) that your friends have to change accordingly to their setup.

  • 1: Create a first version of this class, fill in fields you can fill and leave others empty/null.
  • 2: Commit and push it to the remote server.
  • 3: git update-index --skip-worktree MySetupClass.java
  • 4: Update your configuration class with your own parameters.
  • 5: Go back to work on another functionnality.

The modifications you do will follow you whatever the branch. Warning: if your friends also want to modify this class, they have to have the same setup, otherwise their modifications would be pushed to the remote repository. When pulling, the remote version of the file should overwrite yours.

PS: do one or the other, but not both as you'll have undesirable side-effects. If you want to try another flag, you should disable the latter first.

reading from stdin in c++

You have not defined the variable input_line.

Add this:

string input_line;

And add this include.

#include <string>

Here is the full example. I also removed the semi-colon after the while loop, and you should have getline inside the while to properly detect the end of the stream.

#include <iostream>
#include <string>

int main() {
    for (std::string line; std::getline(std::cin, line);) {
        std::cout << line << std::endl;
    }
    return 0;
}

How to deal with ModalDialog using selenium webdriver?

Solution in R (RSelenium): I had a popup dialog (which is dynamically generated) and hence undetectable in the original page source code Here are methods which worked for me:

Method 1: Simulating Pressing keys for Tabs and switching to that modal dialog My current key is focussed on a dropdown button behind the modal dialog box
remDr$sendKeysToActiveElement(list(key = "tab"))
Sys.sleep(5)
remDr$sendKeysToActiveElement(list(key = "enter"))
Sys.sleep(15)
Method 2: Bring focus to the frame(or iframe) if you can locate it
date_filter_frame <- remDr$findElement(using = "tag name", 'iframe')
date_filter_frame$highlightElement()

Sys.sleep(5)

remDr$switchToFrame(date_filter_frame)

Sys.sleep(2)
Now you can search for elements in the frame. Remember to put adequate Sys.sleep in between commands for elements to load properly (just in case)
date_filter_element <- remDr$findElement(using = "xpath", paste0("//*[contains(text(), 'Week to Date')]"))
date_filter_element$highlightElement()

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

I'm using eclipse neon 3. I just wanted to use javafx.application.Application, so I followed Christian Hujer's answer above and it worked. Just some tips: the access rules are very similar to the import statement. For me, the access rules I added was "javafx/application/**". Just replace the dot in the import statement with forward slash and that's the rule. Hope that helps.

How to use Python's pip to download and keep the zipped files for a package?

installing python packages offline

For windows users:

To download into a file open your cmd and folow this:

cd <*the file-path where you want to save it*>

pip download <*package name*>

the package and the dependencies will be downloaded in the current working directory.

To install from the current working directory:

set your folder where you downloaded as the cwd then follow these:

pip install <*the package name which is downloded as .whl*> --no-index --find-links <*the file locaation where the files are downloaded*>

this will search for dependencies in that location.

What is the default maximum heap size for Sun's JVM from Java SE 6?

As of JDK6U18 following are configurations for the Heap Size.

In the Client JVM, the default Java heap configuration has been modified to improve the performance of today's rich client applications. Initial and maximum heap sizes are larger and settings related to generational garbage collection are better tuned.

The default maximum heap size is half of the physical memory up to a physical memory size of 192 megabytes and otherwise one fourth of the physical memory up to a physical memory size of 1 gigabyte. For example, if your machine has 128 megabytes of physical memory, then the maximum heap size is 64 megabytes, and greater than or equal to 1 gigabyte of physical memory results in a maximum heap size of 256 megabytes. The maximum heap size is not actually used by the JVM unless your program creates enough objects to require it. A much smaller amount, termed the initial heap size, is allocated during JVM initialization. This amount is at least 8 megabytes and otherwise 1/64 of physical memory up to a physical memory size of 1 gigabyte.

Source : http://www.oracle.com/technetwork/java/javase/6u18-142093.html

Installing SciPy with pip

  1. install python-3.4.4
  2. scipy-0.15.1-win32-superpack-python3.4
  3. apply the following commend doc
py -m pip install --upgrade pip
py -m pip install numpy
py -m pip install matplotlib
py -m pip install scipy
py -m pip install scikit-learn

Creating email templates with Django

Boys and Girls!

Since Django's 1.7 in send_email method the html_message parameter was added.

html_message: If html_message is provided, the resulting email will be a multipart/alternative email with message as the text/plain content type and html_message as the text/html content type.

So you can just:

from django.core.mail import send_mail
from django.template.loader import render_to_string


msg_plain = render_to_string('templates/email.txt', {'some_params': some_params})
msg_html = render_to_string('templates/email.html', {'some_params': some_params})

send_mail(
    'email title',
    msg_plain,
    '[email protected]',
    ['[email protected]'],
    html_message=msg_html,
)

Get value when selected ng-option changes

You can pass the ng-model value through the ng-change function as a parameter:

<select 
  ng-model="blisterPackTemplateSelected" 
  data-ng-options="blisterPackTemplate as blisterPackTemplate.name for blisterPackTemplate in blisterPackTemplates" 
  ng-change="changedValue(blisterPackTemplateSelected)">
    <option value="">Select Account</option>
</select>

It's a bit difficult to know your scenario without seeing it, but this should work.

How to open a folder in Windows Explorer from VBA?

Here is what I did.

Dim strPath As String
strPath = "\\server\Instructions\"    
Shell "cmd.exe /c start """" """ & strPath & """", vbNormalFocus

Pros:

  • Avoids opening new explorer instances (only sets focus if window exists).
  • Relatively simple (does not need to reference win32 libraries).
  • Window maximization (or minimization) is not mandatory. Window will open with normal size.

Cons:

  • The cmd-window is visible for a short time.

This consistently opens a window to the folder if there is none open and switches to the open window if there is one open to that folder.

Thanks to PhilHibbs and AnorZaken for the basis for this. PhilHibbs comment didn't quite work for me, I needed to the command string to have a pair of double quotes before the folder name. And I preferred having a command prompt window appear for a bit rather than be forced to have the Explorer window maximized or minimized.

"inconsistent use of tabs and spaces in indentation"

Solving this using Vim editor

  1. Open terminal (Ctrl + Alt + T).
  2. Go to the directory where the file is located (cd <path_to_your_directory>). Ex: cd /home/vineeshvs/work.
  3. Open the file in Vim (vim <file_name>). Ex: vim myfile.txt .
  4. [Optional step] Enable search keyword highlighting in Vim (ESC :set hlsearch)
  5. Go to the line where you have this problem (ESC :<line_number>). Ex: :53 in Vim editor after pressing ESC button once.
  6. Replace tabs using the required number of spaces in Vim (:.,$s/\t/<give_as_many_spaces_as_you_want_to_replace_tab>/gc). Ex: Tab will be replaced with four spaces using the following command: :.,$s/\t/ /gc after pressing ESC button once). This process is interactive. You may give y to replace the tab with spaces and n to skip a particular replacement. Press ESC when you are done with the required replacements.

How can I read command line parameters from an R script?

In bash, you can construct a command line like the following:

$ z=10
$ echo $z
10
$ Rscript -e "args<-commandArgs(TRUE);x=args[1]:args[2];x;mean(x);sd(x)" 1 $z
 [1]  1  2  3  4  5  6  7  8  9 10
[1] 5.5
[1] 3.027650
$

You can see that the variable $z is substituted by bash shell with "10" and this value is picked up by commandArgs and fed into args[2], and the range command x=1:10 executed by R successfully, etc etc.

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

Logging with Retrofit 2

The following set of code is working without any problems for me

Gradle

// Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'

RetrofitClient

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);

OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(logging)
        .build();

retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build();

One can also verify the results by going into Profiler Tab at bottom of Android Studio, then clicking + sign to Start A New Session, and then select the desired spike in "Network". There you can get everything, but it is cumbersome and slow. Please see image below.

enter image description here

How to use __DATE__ and __TIME__ predefined macros in as two integers, then stringify?

Short answer (asked version): (format 3.33.20150710.182906)

Please, simple use a makefile with:

MAJOR = 3
MINOR = 33
BUILD = $(shell date +"%Y%m%d.%H%M%S")
VERSION = "\"$(MAJOR).$(MINOR).$(BUILD)\""
CPPFLAGS = -DVERSION=$(VERSION)

program.x : source.c
       gcc $(CPPFLAGS) source.c -o program.x

and if you don't want a makefile, shorter yet, just compile with:

gcc source.c -o program.x -DVERSION=\"2.22.$(date +"%Y%m%d.%H%M%S")\"

Short answer (suggested version): (format 150710.182906)

Use a double for version number:

MakeFile:

VERSION = $(shell date +"%g%m%d.%H%M%S")
CPPFLAGS = -DVERSION=$(VERSION)
program.x : source.c
      gcc $(CPPFLAGS) source.c -o program.x

Or a simple bash command:

$ gcc source.c -o program.x -DVERSION=$(date +"%g%m%d.%H%M%S")

Tip: Still don't like makefile or is it just for a not-so-small test program? Add this line:

 export CPPFLAGS='-DVERSION='$(date +"%g%m%d.%H%M%S")

to your ~/.profile, and remember compile with gcc $CPPFLAGS ...


Long answer:

I know this question is older, but I have a small contribution to make. Best practice is always automatize what otherwise can became a source of error (or oblivion).

I was used to a function that created the version number for me. But I prefer this function to return a float. My version number can be printed by: printf("%13.6f\n", version()); which issues something like: 150710.150411 (being Year (2 digits) month day DOT hour minute seconds).

But, well, the question is yours. If you prefer "major.minor.date.time", it will have to be a string. (Trust me, double is better. If you insist in a major, you can still use double if you set the major and let the decimals to be date+time, like: major.datetime = 1.150710150411

Lets get to business. The example bellow will work if you compile as usual, forgetting to set it, or use -DVERSION to set the version directly from shell, but better of all, I recommend the third option: use a makefile.


Three forms of compiling and the results:

Using make:

beco> make program.x
gcc -Wall -Wextra -g -O0 -ansi -pedantic-errors -c -DVERSION="\"3.33.20150710.045829\"" program.c -o program.o
gcc  program.o -o program.x

Running:

__DATE__: 'Jul 10 2015'
__TIME__: '04:58:29'
VERSION: '3.33.20150710.045829'

Using -DVERSION:

beco> gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors -DVERSION=\"2.22.$(date +"%Y%m%d.%H%M%S")\"

Running:

__DATE__: 'Jul 10 2015'
__TIME__: '04:58:37'
VERSION: '2.22.20150710.045837'

Using the build-in function:

beco> gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors

Running:

__DATE__: 'Jul 10 2015'
__TIME__: '04:58:43'
VERSION(): '1.11.20150710.045843'

Source code

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4 
  5 #define FUNC_VERSION (0)
  6 #ifndef VERSION
  7   #define MAJOR 1
  8   #define MINOR 11
  9   #define VERSION version()
 10   #undef FUNC_VERSION
 11   #define FUNC_VERSION (1)
 12   char sversion[]="9999.9999.20150710.045535";
 13 #endif
 14 
 15 #if(FUNC_VERSION)
 16 char *version(void);
 17 #endif
 18 
 19 int main(void)
 20 {
 21 
 22   printf("__DATE__: '%s'\n", __DATE__);
 23   printf("__TIME__: '%s'\n", __TIME__);
 24 
 25   printf("VERSION%s: '%s'\n", (FUNC_VERSION?"()":""), VERSION);
 26   return 0;
 27 }
 28 
 29 /* String format: */
 30 /* __DATE__="Oct  8 2013" */
 31 /*  __TIME__="00:13:39" */
 32
 33 /* Version Function: returns the version string */
 34 #if(FUNC_VERSION)
 35 char *version(void)
 36 {
 37   const char data[]=__DATE__;
 38   const char tempo[]=__TIME__;
 39   const char nomes[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
 40   char omes[4];
 41   int ano, mes, dia, hora, min, seg;
 42 
 43   if(strcmp(sversion,"9999.9999.20150710.045535"))
 44     return sversion;
 45 
 46   if(strlen(data)!=11||strlen(tempo)!=8)
 47     return NULL;
 48 
 49   sscanf(data, "%s %d %d", omes, &dia, &ano);
 50   sscanf(tempo, "%d:%d:%d", &hora, &min, &seg);
 51   mes=(strstr(nomes, omes)-nomes)/3+1;
 52   sprintf(sversion,"%d.%d.%04d%02d%02d.%02d%02d%02d", MAJOR, MINOR, ano, mes, dia, hora, min, seg);
 53 
 54   return sversion;
 55 }
 56 #endif

Please note that the string is limited by MAJOR<=9999 and MINOR<=9999. Of course, I set this high value that will hopefully never overflow. But using double is still better (plus, it's completely automatic, no need to set MAJOR and MINOR by hand).

Now, the program above is a bit too much. Better is to remove the function completely, and guarantee that the macro VERSION is defined, either by -DVERSION directly into GCC command line (or an alias that automatically add it so you can't forget), or the recommended solution, to include this process into a makefile.

Here it is the makefile I use:


MakeFile source:

  1   MAJOR = 3
  2   MINOR = 33
  3   BUILD = $(shell date +"%Y%m%d.%H%M%S")
  4   VERSION = "\"$(MAJOR).$(MINOR).$(BUILD)\""
  5   CC = gcc
  6   CFLAGS = -Wall -Wextra -g -O0 -ansi -pedantic-errors
  7   CPPFLAGS = -DVERSION=$(VERSION)
  8   LDLIBS =
  9   
 10    %.x : %.c
 11          $(CC) $(CFLAGS) $(CPPFLAGS) $(LDLIBS) $^ -o $@

A better version with DOUBLE

Now that I presented you "your" preferred solution, here it is my solution:

Compile with (a) makefile or (b) gcc directly:

(a) MakeFile:

   VERSION = $(shell date +"%g%m%d.%H%M%S")
   CC = gcc
   CFLAGS = -Wall -Wextra -g -O0 -ansi -pedantic-errors 
   CPPFLAGS = -DVERSION=$(VERSION)
   LDLIBS =
   %.x : %.c
         $(CC) $(CFLAGS) $(CPPFLAGS) $(LDLIBS) $^ -o $@

(b) Or a simple bash command:

 $ gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors -DVERSION=$(date +"%g%m%d.%H%M%S")

Source code (double version):

#ifndef VERSION
  #define VERSION version()
#endif

double version(void);

int main(void)
{
  printf("VERSION%s: '%13.6f'\n", (FUNC_VERSION?"()":""), VERSION);
  return 0;
}

double version(void)
{
  const char data[]=__DATE__;
  const char tempo[]=__TIME__;
  const char nomes[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  char omes[4];
  int ano, mes, dia, hora, min, seg;
  char sversion[]="130910.001339";
  double fv;

  if(strlen(data)!=11||strlen(tempo)!=8)
    return -1.0;

  sscanf(data, "%s %d %d", omes, &dia, &ano);
  sscanf(tempo, "%d:%d:%d", &hora, &min, &seg);
  mes=(strstr(nomes, omes)-nomes)/3+1;
  sprintf(sversion,"%04d%02d%02d.%02d%02d%02d", ano, mes, dia, hora, min, seg);
  fv=atof(sversion);

  return fv;
}

Note: this double function is there only in case you forget to define macro VERSION. If you use a makefile or set an alias gcc gcc -DVERSION=$(date +"%g%m%d.%H%M%S"), you can safely delete this function completely.


Well, that's it. A very neat and easy way to setup your version control and never worry about it again!

Laravel PDOException SQLSTATE[HY000] [1049] Unknown database 'forge'

In my case the error was due to incorrect port number (the error is definitely due to incorrect credentials i.e. host/port/dbname/username/password).

Solution:

  1. right click on WAMP tray;
  2. click (drag your cursor) on MySQL;
  3. see the port number used by MySQL;
  4. add same in your Laravel configuration:
    • .env file;
    • config/database.php.

Clear cache php artisan config:cache

Run migration php artisan migrate

HTML: Select multiple as dropdown

Here is the documentation of <select>. You are using 2 attributes:

multiple
This Boolean attribute indicates that multiple options can be selected in the list. If it is not specified, then only one option can be selected at a time. When multiple is specified, most browsers will show a scrolling list box instead of a single line dropdown.

size
If the control is presented as a scrolling list box (e.g. when multiple is specified), this attribute represents the number of rows in the list that should be visible at one time. Browsers are not required to present a select element as a scrolled list box. The default value is 0.

As described in the docs. <select size="1" multiple> will render a List box only 1 line visible and a scrollbar. So you are loosing the dropdown/arrow with the multiple attribute.

ERROR Error: No value accessor for form control with unspecified name attribute on switch

Have you tried moving your [(ngModel)] to the div instead of the switch in your HTML? I had the same error appear in my code and it was because I bound the model to a <mat-option> instead of a <mat-select>. Though I am not using form control.

How to negate the whole regex?

Apply this if you use laravel.

Laravel has a not_regex where field under validation must not match the given regular expression; uses the PHP preg_match function internally.

'email' => 'not_regex:/^.+$/i'

How to echo or print an array in PHP?

You have no need to put for loop to see the data into the array, you can simply do in following manner

<?php
echo "<pre>";
 print_r($results); 
echo "</pre>";
?>

How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()

In my case I had to wait for a user interaction, so I set a click or touchend listener.

const isMobile = navigator.maxTouchPoints || "ontouchstart" in document.documentElement;

function play(){
    audioEl.play()
}


document.body.addEventListener(isMobile ? "touchend" : "click", play, { once: true });

JavaScript closures vs. anonymous functions

I would like to share my example and an explanation about closures. I made a python example, and two figures to demonstrate stack states.

def maker(a, b, n):
    margin_top = 2
    padding = 4
    def message(msg):
        print('\n’ * margin_top, a * n, 
            ' ‘ * padding, msg, ' ‘ * padding, b * n)
    return message

f = maker('*', '#', 5)
g = maker('?', '?’, 3)
…
f('hello')
g(‘good bye!')

The output of this code would be as follows:

*****      hello      #####

???      good bye!    ???

Here are two figures to show stacks and the closure attached to the function object.

when the function is returned from maker

when the function is called later

When the function is called through a parameter or a nonlocal variable, the code needs local variable bindings such as margin_top, padding as well as a, b, n. In order to ensure the function code to work, the stack frame of the maker function which was gone away long ago should be accessible, which is backed up in the closure we can find along with the function message object.

What does mscorlib stand for?

Microsoft Core Library, ie they are at the heart of everything.

There is a more "massaged" explanation you may prefer:

"When Microsoft first started working on the .NET Framework, MSCorLib.dll was an acronym for Microsoft Common Object Runtime Library. Once ECMA started to standardize the CLR and parts of the FCL, MSCorLib.dll officially became the acronym for Multilanguage Standard Common Object Runtime Library."

From http://weblogs.asp.net/mreynolds/archive/2004/01/31/65551.aspx

Around 1999, to my personal memory, .Net was known as "COOL", so I am a little suspicious of this derivation. I never heard it called "COR", which is a silly-sounding name to a native English speaker.

Add a list item through javascript

Try something like this:

var node=document.createElement("LI");
var textnode=document.createTextNode(firstname);
node.appendChild(textnode);
document.getElementById("demo").appendChild(node);

Fiddle: http://jsfiddle.net/FlameTrap/3jDZd/

How to print a dictionary line by line in Python?

Here is my solution to the problem. I think it's similar in approach, but a little simpler than some of the other answers. It also allows for an arbitrary number of sub-dictionaries and seems to work for any datatype (I even tested it on a dictionary which had functions as values):

def pprint(web, level):
    for k,v in web.items():
        if isinstance(v, dict):
            print('\t'*level, f'{k}: ')
            level += 1
            pprint(v, level)
            level -= 1
        else:
            print('\t'*level, k, ": ", v)

Why dividing two integers doesn't get a float?

Chapter and verse

6.5.5 Multiplicative operators
...
6 When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.105) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a; otherwise, the behavior of both a/b and a%b is unde?ned.

105) This is often called ‘‘truncation toward zero’’.

Dividing an integer by an integer gives an integer result. 1/2 yields 0; assigning this result to a floating-point variable gives 0.0. To get a floating-point result, at least one of the operands must be a floating-point type. b = a / 350.0f; should give you the result you want.

What is the best way to do a substring in a batch file?

As an additional info to Joey's answer, which isn't described in the help of set /? nor for /?.

%~0 expands to the name of the own batch, exactly as it was typed.
So if you start your batch it will be expanded as

%~0   - mYbAtCh
%~n0  - mybatch
%~nx0 - mybatch.bat

But there is one exception, expanding in a subroutine could fail

echo main- %~0
call :myFunction
exit /b

:myFunction
echo func - %~0
echo func - %~n0
exit /b

This results to

main - myBatch
Func - :myFunction
func - mybatch

In a function %~0 expands always to the name of the function, not of the batch file.
But if you use at least one modifier it will show the filename again!

Getting Access Denied when calling the PutObject operation with bucket-level permission

In case this help out anyone else, in my case, I was using a CMK (it worked fine using the default aws/s3 key)

I had to go into my encryption key definition in IAM and add the programmatic user logged into boto3 to the list of users that "can use this key to encrypt and decrypt data from within applications and when using AWS services integrated with KMS.".

How do I clone a generic list in C#?

There is no need to flag classes as Serializable and in our tests using the Newtonsoft JsonSerializer even faster than using BinaryFormatter. With extension methods usable on every object.

Standard .NET JavascriptSerializer option:

public static T DeepCopy<T>(this T value)
{
    JavaScriptSerializer js = new JavaScriptSerializer();

    string json = js.Serialize(value);

    return js.Deserialize<T>(json);
}

Faster option using Newtonsoft JSON:

public static T DeepCopy<T>(this T value)
{
    string json = JsonConvert.SerializeObject(value);

    return JsonConvert.DeserializeObject<T>(json);
}

A completely free agile software process tool

EDIT: Kanbanize is a commercial product and offers a 30 day free trial.

Disclosing: I am a co-founder of http://kanbanize.com/

Mark, I understand your desire to find the perfect application with all these features inside, but I really doubt that you will get it for free. There's a bunch of super cool apps (including Kanbanize) out there, but none of them is completely free.

Be careful what you call a Kanban board and what not, though. Trello is definitely NOT a kanban system (no WIP limits, no analytics, etc.). It is a great visual management system, but not a Kanban one.

Finally, to answer your question, tools that deserve attention in my opinion are: Kanbanize (of course), LeanKit, KanbanTool, Kanbanery and probably a few others. My personal bias is that LeanKit is the most advanced to date followed by Kanbanize and KanbanTool.

I hope that helps.

How to get the number of characters in a std::string?

If you're using a std::string, call length():

std::string str = "hello";
std::cout << str << ":" << str.length();
// Outputs "hello:5"

If you're using a c-string, call strlen().

const char *str = "hello";
std::cout << str << ":" << strlen(str);
// Outputs "hello:5"

Or, if you happen to like using Pascal-style strings (or f***** strings as Joel Spolsky likes to call them when they have a trailing NULL), just dereference the first character.

const char *str = "\005hello";
std::cout << str + 1 << ":" << *str;
// Outputs "hello:5"

How do I reload a page without a POSTDATA warning in Javascript?

You can use JavaScript:

window.location.assign(document.URL);

Worked for me on Firefox and Chrome

check this link: http://www.codeproject.com/Tips/433399/PRG-Pattern-Post-Redirect-Get

Error: Java: invalid target release: 11 - IntelliJ IDEA

Below changes worked for me and hope the same works for you.

  1. Change the version of Java from 11 to 8 in pom.xml file
    <java.version>1.8</java.version>

  2. Go to, File -> Settings -> Build, Execution, Deployment -> Compiler -> Java Compiler
    Here, in Module column you can see your project listed and in Target bytecode version column, Java version for the project is already specified(mostly 11), change it to 8

  3. Go to, File -> Project Structure -> Modules. Here, in Source tab, you can see Language level option, choose 8 - Lambdas, type annotations etc.. Finally, choose Apply and OK, you're good to go.

How to get a MemoryStream from a Stream in .NET?

In .NET 4, you can use Stream.CopyTo to copy a stream, instead of the home-brew methods listed in the other answers.

MemoryStream _ms;

public MyClass(Stream sourceStream)

    _ms = new MemoryStream();
    sourceStream.CopyTo(_ms);
}

Determine path of the executing script

You can wrap the r script in a bash script and retrieve the script's path as a bash variable like so:

#!/bin/bash
     # [environment variables can be set here]
     path_to_script=$(dirname $0)

     R --slave<<EOF
        source("$path_to_script/other.R")

     EOF

Rotating and spacing axis labels in ggplot2

OUTDATED - see this answer for a simpler approach


To obtain readable x tick labels without additional dependencies, you want to use:

  ... +
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5)) +
  ...

This rotates the tick labels 90° counterclockwise and aligns them vertically at their end (hjust = 1) and their centers horizontally with the corresponding tick mark (vjust = 0.5).

Full example:

library(ggplot2)
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))
q <- qplot(cut,carat,data=diamonds,geom="boxplot")
q + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))


Note, that vertical/horizontal justification parameters vjust/hjust of element_text are relative to the text. Therefore, vjust is responsible for the horizontal alignment.

Without vjust = 0.5 it would look like this:

q + theme(axis.text.x = element_text(angle = 90, hjust = 1))

Without hjust = 1 it would look like this:

q + theme(axis.text.x = element_text(angle = 90, vjust = 0.5))

If for some (wired) reason you wanted to rotate the tick labels 90° clockwise (such that they can be read from the left) you would need to use: q + theme(axis.text.x = element_text(angle = -90, vjust = 0.5, hjust = -1)).

All of this has already been discussed in the comments of this answer but I come back to this question so often, that I want an answer from which I can just copy without reading the comments.

Split column at delimiter in data frame

@Taesung Shin is right, but then just some more magic to make it into a data.frame. I added a "x|y" line to avoid ambiguities:

df <- data.frame(ID=11:13, FOO=c('a|b','b|c','x|y'))
foo <- data.frame(do.call('rbind', strsplit(as.character(df$FOO),'|',fixed=TRUE)))

Or, if you want to replace the columns in the existing data.frame:

within(df, FOO<-data.frame(do.call('rbind', strsplit(as.character(FOO), '|', fixed=TRUE))))

Which produces:

  ID FOO.X1 FOO.X2
1 11      a      b
2 12      b      c
3 13      x      y

Calculate rolling / moving average in C++

If your needs are simple, you might just try using an exponential moving average.

http://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average

Put simply, you make an accumulator variable, and as your code looks at each sample, the code updates the accumulator with the new value. You pick a constant "alpha" that is between 0 and 1, and compute this:

accumulator = (alpha * new_value) + (1.0 - alpha) * accumulator

You just need to find a value of "alpha" where the effect of a given sample only lasts for about 1000 samples.

Hmm, I'm not actually sure this is suitable for you, now that I've put it here. The problem is that 1000 is a pretty long window for an exponential moving average; I'm not sure there is an alpha that would spread the average over the last 1000 numbers, without underflow in the floating point calculation. But if you wanted a smaller average, like 30 numbers or so, this is a very easy and fast way to do it.

Where is the .NET Framework 4.5 directory?

EDIT: This answer was correct until mid-2013, but you may have a more recent version since the big msbuild change. See the answer from Jonny Leeds for more details.

The version under C:\Windows\Microsoft.NET\Framework\v4.0.30319 actually is .NET 4.5. It's a little odd, but certainly mscorlib there contains AsyncTaskMethodBuilder etc which are used for async.

.NET 4.5 effectively overwrites .NET 4.

Replace words in the body text

I was trying to replace a really large string and for some reason regular expressions were throwing some errors/exceptions.

So I found this alternative to regular expressions which also runs pretty fast. At least it was fast enough for me:

var search = "search string";
var replacement = "replacement string";

document.body.innerHTML = document.body.innerHTML.split(search).join(replacement)

src: How to replace all occurrences of a string in JavaScript?

How to trim leading and trailing white spaces of a string?

@peterSO has correct answer. I am adding more examples here:

package main

import (
    "fmt"
    strings "strings"
)

func main() { 
    test := "\t pdftk 2.0.2  \n"
    result := strings.TrimSpace(test)
    fmt.Printf("Length of %q is %d\n", test, len(test))
    fmt.Printf("Length of %q is %d\n\n", result, len(result))

    test = "\n\r pdftk 2.0.2 \n\r"
    result = strings.TrimSpace(test)
    fmt.Printf("Length of %q is %d\n", test, len(test))
    fmt.Printf("Length of %q is %d\n\n", result, len(result))

    test = "\n\r\n\r pdftk 2.0.2 \n\r\n\r"
    result = strings.TrimSpace(test)
    fmt.Printf("Length of %q is %d\n", test, len(test))
    fmt.Printf("Length of %q is %d\n\n", result, len(result))

    test = "\r pdftk 2.0.2 \r"
    result = strings.TrimSpace(test)
    fmt.Printf("Length of %q is %d\n", test, len(test))
    fmt.Printf("Length of %q is %d\n\n", result, len(result))   
}

You can find this in Go lang playground too.

No visible cause for "Unexpected token ILLEGAL"

The error

When code is parsed by the JavaScript interpreter, it gets broken into pieces called "tokens". When a token cannot be classified into one of the four basic token types, it gets labelled "ILLEGAL" on most implementations, and this error is thrown.

The same error is raised if, for example, you try to run a js file with a rogue @ character, a misplaced curly brace, bracket, "smart quotes", single quotes not enclosed properly (e.g. this.run('dev1)) and so on.

A lot of different situations can cause this error. But if you don't have any obvious syntax error or illegal character, it may be caused by an invisible illegal character. That's what this answer is about.

But I can't see anything illegal!

There is an invisible character in the code, right after the semicolon. It's the Unicode U+200B Zero-width space character (a.k.a. ZWSP, HTML entity &#8203;). That character is known to cause the Unexpected token ILLEGAL JavaScript syntax error.

And where did it come from?

I can't tell for sure, but my bet is on jsfiddle. If you paste code from there, it's very likely to include one or more U+200B characters. It seems the tool uses that character to control word-wrapping on long strings.

UPDATE 2013-01-07

After the latest jsfiddle update, it's now showing the character as a red dot like codepen does. Apparently, it's also not inserting U+200B characters on its own anymore, so this problem should be less frequent from now on.

UPDATE 2015-03-17

Vagrant appears to sometimes cause this issue as well, due to a bug in VirtualBox. The solution, as per this blog post is to set sendfile off; in your nginx config, or EnableSendfile Off if you use Apache.

It's also been reported that code pasted from the Chrome developer tools may include that character, but I was unable to reproduce that with the current version (22.0.1229.79 on OSX).

How can I spot it?

The character is invisible, do how do we know it's there? You can ask your editor to show invisible characters. Most text editors have this feature. Vim, for example, displays them by default, and the ZWSP shows as <u200b>. You can also debug it online: jsbin displays the character as a red dot on its code panes (but seems to remove it after saving and reloading the page). CodePen.io also displays it as a dot, and keeps it even after saving.

Related problems

That character is not something bad, it can actually be quite useful. This example on Wikipedia demonstrates how it can be used to control where a long string should be wrapped to the next line. However, if you are unaware of the character's presence on your markup, it may become a problem. If you have it inside of a string (e.g., the nodeValue of a DOM element that has no visible content), you might expect such string to be empty, when in fact it's not (even after applying String.trim).

ZWSP can also cause extra whitespace to be displayed on an HTML page, for example when it's found between two <div> elements (as seen on this question). This case is not even reproducible on jsfiddle, since the character is ignored there.

Another potential problem: if the web page's encoding is not recognized as UTF-8, the character may actually be displayed (as ​ in latin1, for example).

If ZWSP is present on CSS code (inline code, or an external stylesheet), styles can also not be parsed properly, so some styles don't get applied (as seen on this question).

The ECMAScript Specification

I couldn't find any mention to that specific character on the ECMAScript Specification (versions 3 and 5.1). The current version mentions similar characters (U+200C and U+200D) on Section 7.1, which says they should be treated as IdentifierParts when "outside of comments, string literals, and regular expression literals". Those characters may, for example, be part of a variable name (and var x\u200c; indeed works).

Section 7.2 lists the valid White space characters (such as tab, space, no-break space, etc.), and vaguely mentions that any other Unicode “space separator” (category “Zs”) should be treated as white space. I'm probably not the best person to discuss the specs in this regard, but it seems to me that U+200B should be considered white space according to that, when in fact the implementations (at least Chrome and Firefox) appear to treat them as an unexpected token (or part of one), causing the syntax error.

Get the height and width of the browser viewport without scrollbars using jquery?

I wanted a different look of my website for width screen and small screen. I have made 2 CSS files. In Java I choose which of the 2 CSS file is used depending on the screen width. I use the PHP function echo with in the echo-function some javascript.

my code in the <header> section of my PHP-file:

<?php
echo "
<script>
    if ( window.innerWidth > 400)
            { document.write('<link href=\"kekemba_resort_stylesheetblog-jun2018.css\" rel=\"stylesheet\" type=\"text/css\">'); }
    else
            { document.write('<link href=\"kekemba_resort_stylesheetblog-jun2018small.css\" rel=\"stylesheet\" type=\"text/css\">'); }
</script>
"; 
?>

Get current controller in view

I do it like this, but perhaps it's only ASP.NET MVC 4

@ViewContext.RouteData.Values["controller"]

How do you set autocommit in an SQL Server session?

You can turn autocommit ON by setting implicit_transactions OFF:

SET IMPLICIT_TRANSACTIONS OFF

When the setting is ON, it returns to implicit transaction mode. In implicit transaction mode, every change you make starts a transactions which you have to commit manually.

Maybe an example is clearer. This will write a change to the database:

SET IMPLICIT_TRANSACTIONS ON
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
COMMIT TRANSACTION

This will not write a change to the database:

SET IMPLICIT_TRANSACTIONS ON
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
ROLLBACK TRANSACTION

The following example will update a row, and then complain that there's no transaction to commit:

SET IMPLICIT_TRANSACTIONS OFF
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
ROLLBACK TRANSACTION

Like Mitch Wheat said, autocommit is the default for Sql Server 2000 and up.

How do I make a simple crawler in PHP?

Meh. Don't parse HTML with regexes.

Here's a DOM version inspired by Tatu's:

<?php
function crawl_page($url, $depth = 5)
{
    static $seen = array();
    if (isset($seen[$url]) || $depth === 0) {
        return;
    }

    $seen[$url] = true;

    $dom = new DOMDocument('1.0');
    @$dom->loadHTMLFile($url);

    $anchors = $dom->getElementsByTagName('a');
    foreach ($anchors as $element) {
        $href = $element->getAttribute('href');
        if (0 !== strpos($href, 'http')) {
            $path = '/' . ltrim($href, '/');
            if (extension_loaded('http')) {
                $href = http_build_url($url, array('path' => $path));
            } else {
                $parts = parse_url($url);
                $href = $parts['scheme'] . '://';
                if (isset($parts['user']) && isset($parts['pass'])) {
                    $href .= $parts['user'] . ':' . $parts['pass'] . '@';
                }
                $href .= $parts['host'];
                if (isset($parts['port'])) {
                    $href .= ':' . $parts['port'];
                }
                $href .= dirname($parts['path'], 1).$path;
            }
        }
        crawl_page($href, $depth - 1);
    }
    echo "URL:",$url,PHP_EOL,"CONTENT:",PHP_EOL,$dom->saveHTML(),PHP_EOL,PHP_EOL;
}
crawl_page("http://hobodave.com", 2);

Edit: I fixed some bugs from Tatu's version (works with relative URLs now).

Edit: I added a new bit of functionality that prevents it from following the same URL twice.

Edit: echoing output to STDOUT now so you can redirect it to whatever file you want

Edit: Fixed a bug pointed out by George in his answer. Relative urls will no longer append to the end of the url path, but overwrite it. Thanks to George for this. Note that George's answer doesn't account for any of: https, user, pass, or port. If you have the http PECL extension loaded this is quite simply done using http_build_url. Otherwise, I have to manually glue together using parse_url. Thanks again George.

add id to dynamically created <div>

Use Jquery for append the value for creating dynamically

eg:

var user_image1='<img src="{@user_image}" class="img-thumbnail" alt="Thumbnail Image" 
style="width:125px; height:125px">';

$("#userphoto").append(user_image1.replace("{@user_image}","http://127.0.0.1:50075/webhdfs/v1/PATH/"+user_image+"?op=OPEN")); 

HTML :

<div id="userphoto">

Get list of passed arguments in Windows batch script (.bat)

@echo off
:start

:: Insert your code here
echo.%%1 is now:%~1
:: End insert your code here

if "%~2" NEQ "" (
    shift
    goto :start
)

Selecting with complex criteria from pandas.DataFrame

And remember to use parenthesis!

Keep in mind that & operator takes a precedence over operators such as > or < etc. That is why

4 < 5 & 6 > 4

evaluates to False. Therefore if you're using pd.loc, you need to put brackets around your logical statements, otherwise you get an error. That's why do:

df.loc[(df['A'] > 10) & (df['B'] < 15)]

instead of

df.loc[df['A'] > 10 & df['B'] < 15]

which would result in

TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

The error you get is due to the CORS standard, which sets some restrictions on how JavaScript can perform ajax requests.

The CORS standard is a client-side standard, implemented in the browser. So it is the browser which prevent the call from completing and generates the error message - not the server.

Postman does not implement the CORS restrictions, which is why you don't see the same error when making the same call from Postman.

How to export a table dataframe in PySpark to csv?

You need to repartition the Dataframe in a single partition and then define the format, path and other parameter to the file in Unix file system format and here you go,

df.repartition(1).write.format('com.databricks.spark.csv').save("/path/to/file/myfile.csv",header = 'true')

Read more about the repartition function Read more about the save function

However, repartition is a costly function and toPandas() is worst. Try using .coalesce(1) instead of .repartition(1) in previous syntax for better performance.

Read more on repartition vs coalesce functions.

What are App Domains in Facebook Apps?

It's simply the domain that your "facebook" application (wich means application visible on facebook but hosted on the website www.xyz.com) will be hosted. So you can put App Domain = www.xyz.com

Error 1053 the service did not respond to the start or control request in a timely fashion

In my case, the issue was about caching configuration which is set in the App.config file. Once I removed below lines from the App.config file, the issue was resolved.

<cachingConfiguration defaultCacheManager="MyCacheManager">
<cacheManagers>
  <add name="MyCacheManager" type="Microsoft.Practices.EnterpriseLibrary.Caching.CacheManager, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
       expirationPollFrequencyInSeconds="60"
       maximumElementsInCacheBeforeScavenging="50000"
       numberToRemoveWhenScavenging="1000"
       backingStoreName="NullBackingStore" />
</cacheManagers>
<backingStores>
  <add type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.NullBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
       name="NullBackingStore" />
</backingStores>

How to set Spring profile from system variable?

You can set the spring profile by supplying -Dspring.profiles.active=<env>

For java files in source(src) directory, you can use by System.getProperty("spring.profiles.active")

For java files in test directory you can supply

  • SPRING_PROFILES_ACTIVE to <env>

OR

Since, "environment", "jvmArgs" and "systemProperties" are ignored for the "test" task. In root build.gradle add a task to set jvm property and environment variable.

test {
    def profile = System.properties["spring.profiles.active"]
    systemProperty "spring.profiles.active",profile
    environment "SPRING.PROFILES_ACTIVE", profile
    println "Running ${project} tests with profile: ${profile}"
}

jquery Ajax call - data parameters are not being passed to MVC Controller action

If you have trouble with caching ajax you can turn it off:

$.ajaxSetup({cache: false});

How do I retrieve an HTML element's actual width and height?

You only need to calculate it for IE7 and older (and only if your content doesn't have fixed size). I suggest using HTML conditional comments to limit hack to old IEs that don't support CSS2. For all other browsers use this:

<style type="text/css">
    html,body {display:table; height:100%;width:100%;margin:0;padding:0;}
    body {display:table-cell; vertical-align:middle;}
    div {display:table; margin:0 auto; background:red;}
</style>
<body><div>test<br>test</div></body>

This is the perfect solution. It centers <div> of any size, and shrink-wraps it to size of its content.

facet label font size

This should get you started:

R> qplot(hwy, cty, data = mpg) + 
       facet_grid(. ~ manufacturer) + 
       theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))

See also this question: How can I manipulate the strip text of facet plots in ggplot2?

How do you tell if caps lock is on using JavaScript?

This jQuery-based answer posted by @user110902 was useful for me. However, I improved it a little to prevent a flaw mentioned in @B_N 's comment: it failed detecting CapsLock while you press Shift:

$('#example').keypress(function(e) { 
    var s = String.fromCharCode( e.which );
    if (( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey )
    ||  ( s.toLowerCase() === s && s.toUpperCase() !== s && e.shiftKey )) {
        alert('caps is on');
    }
});

Like this, it will work even while pressing Shift.

How to urlencode a querystring in Python?

Try this:

urllib.pathname2url(stringToURLEncode)

urlencode won't work because it only works on dictionaries. quote_plus didn't produce the correct output.

Determine SQL Server Database Size

You could use this old fashioned one as well...

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

DECLARE @iCount int, @iMax int, @DatabaseName varchar(200), @SQL varchar (8000)

Select NAME, DBID, crdate, filename, version 
INTO #TEMP
from MAster..SYSDatabASES 

SELECT @iCount = Count(DBID) FROM #TEMP

Select @SQL='Create Table ##iFile1 ( DBName varchar( 200) NULL, Fileid INT, FileGroup int, TotalExtents INT , USedExtents INT , 
Name varchar(100), vFile varchar (300), AllocatedSpace int NUll, UsedSpace int Null, PercentageFree int Null ) '+ char(10)
exec (@SQL)


Create Table ##iTotals ( ServerName varchar(100), DBName varchar( 200) NULL, FileType varchar(10),Fileid INT, FileGroup int, TotalExtents INT , USedExtents INT , 
Name varchar(100), vFile varchar (300), AllocatedSpace int NUll, UsedSpace int Null, PercentageFree int Null ) 


WHILE @iCount>0
BEGIN    
    SELECT @iMax =Max(dbid) FROM #TEMP
    Select @DatabaseName = Name FROM #TEMP where dbid =@iMax

    SELECT @SQL = 'INSERT INTO ##iFile1(Fileid , FileGroup , TotalExtents  , USedExtents  , Name , vFile)
     EXEC (''USE [' + @DatabaseName +  '] DBCC showfilestats'')    ' + char(10)

    Print  (@SQL)
    EXEC (@SQL)


    SELECT @SQL = 'UPDATE ##iFile1 SET DBName ='''+ @DatabaseName +''' WHERE DBName IS NULL'
    EXEC  (@SQL)


    DELETE FROM #TEMP WHERE dbid =@iMax
    Select @iCount =@iCount -1
END
UPDATE ##iFile1
SET AllocatedSpace = (TotalExtents * 64.0 / 1024.0 ), UsedSpace =(USedExtents * 64.0 / 1024.0 )

UPDATE ##iFile1
SET PercentageFree = 100-Convert(float,UsedSpace)/Convert(float,AllocatedSpace   )* 100
WHERE USEDSPACE>0

CREATE TABLE #logspace (
   DBName varchar( 100),
   LogSize float,
   PrcntUsed float,
   status int
   )
INSERT INTO #logspace
EXEC ('DBCC sqlperf( logspace)')



INSERT INTO ##iTotals(ServerName, DBName, FileType,Name, vFile,PercentageFree,AllocatedSpace)
select @@ServerName ,DBNAME,  'Data' as FileType,Name, vFile, PercentageFree  , AllocatedSpace
from ##iFile1
UNION
select @@ServerName ,DBNAME, 'Log' as FileType ,DBName,'' as vFile ,PrcntUsed  , LogSize
from #logspace

Select * from ##iTotals

select ServerName ,DBNAME,  FileType, Sum( AllocatedSpace) as AllocatedSpaceMB
from ##iTotals
Group By  ServerName ,DBNAME, FileType
Order By  ServerName ,DBNAME, FileType


select ServerName ,DBNAME,  Sum( AllocatedSpace) as AllocatedSpaceMB
from ##iTotals
Group By  ServerName ,DBNAME
Order By  ServerName ,DBNAME



drop table ##iFile1
drop table #logspace
drop table #TEMP
drop table ##iTotals

Export pictures from excel file into jpg using VBA

New versions of excel have made old answers obsolete. It took a long time to make this, but it does a pretty good job. Note that the maximum image size is limited and the aspect ratio is ever so slightly off, as I was not able to perfectly optimize the reshaping math. Note that I've named one of my worksheets wsTMP, you can replace it with Sheet1 or the like. Takes about 1 second to print the screenshot to target path.

Option Explicit

Private Declare PtrSafe Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)

Sub weGucciFam()

Dim tmp As Variant, str As String, h As Double, w As Double

Application.PrintCommunication = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
If Application.StatusBar = False Then Application.StatusBar = "EVENTS DISABLED"

keybd_event vbKeyMenu, 0, 0, 0 'these do just active window
keybd_event vbKeySnapshot, 0, 0, 0
keybd_event vbKeySnapshot, 0, 2, 0
keybd_event vbKeyMenu, 0, 2, 0 'sendkeys alt+printscreen doesn't work
wsTMP.Paste
DoEvents
Const dw As Double = 1186.56
Const dh As Double = 755.28

str = "C:\Users\YOURUSERNAMEHERE\Desktop\Screenshot.jpeg"
w = wsTMP.Shapes(1).Width
h = wsTMP.Shapes(1).Height

Application.DisplayAlerts = False
Set tmp = Charts.Add
On Error Resume Next
With tmp
    .PageSetup.PaperSize = xlPaper11x17
    .PageSetup.TopMargin = IIf(w > dw, dh - dw * h / w, dh - h) + 28
    .PageSetup.BottomMargin = 0
    .PageSetup.RightMargin = IIf(h > dh, dw - dh * w / h, dw - w) + 36
    .PageSetup.LeftMargin = 0
    .PageSetup.HeaderMargin = 0
    .PageSetup.FooterMargin = 0
    .SeriesCollection(1).Delete
    DoEvents
    .Paste
    DoEvents
    .Export Filename:=str, Filtername:="jpeg"
    .Delete
End With
On Error GoTo 0
Do Until wsTMP.Shapes.Count < 1
    wsTMP.Shapes(1).Delete
Loop

Application.PrintCommunication = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.StatusBar = False

End Sub

Bootstrap Align Image with text

_x000D_
_x000D_
<div class="container">_x000D_
     <h1>About Me</h1>_x000D_
    <div class="row">_x000D_
        <div class="col-md-4">_x000D_
            <div class="imgAbt">_x000D_
                <img width="100%" height="100%" src="img/me.jpg" />_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="col-md-8">_x000D_
            <p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Calculating and printing the nth prime number

I just added the missing lines in your own thought process.

static int nthPrimeFinder(int n) {

        int counter = 1; // For 1 and 2. assuming n is not 1 or 2.
        int i = 2;
        int x = 2;
        int tempLength = n;

        while (counter <= n) {
            for (; i <= tempLength; i++) {
                for (x = 2; x < i; x++) {
                    if (i % x == 0) {
                        break;
                    }
                }
                if (x == i && counter < n) {
                    //System.out.printf("\n%d is prime", x);
                    counter++;
                    if (counter == n) {
                        System.out.printf("\n%d is prime", x);
                        return counter;
                    }
                }
            }
            tempLength = tempLength+n;
        }
        return 0;
    }

How to fix date format in ASP .NET BoundField (DataFormatString)?

Determine the data type of your data source column, "CreateDate". Make sure it is producing an actual datetime field and not something like a varchar. If your data source is a stored procedure, it is entirely possible that CreateDate is being processed to produce a varchar in order to format the date, like so:

SELECT CONVERT(varchar,TableName.CreateDate,126) AS CreateDate 
FROM TableName ...

Using CONVERT like this is often done to make query results fill the requirements of whatever other code is going to be processing those results. Style 126 is ISO 8601 format, an international standard that works with any language setting. I don't know what your industry is, but that was probably intentional. You don't want to mess with it. This style (126) produces a string representation of a date in the form '2013-04-29T18:15:20.270' just like you reported! However, if CreateDate's been processed this way then there's no way you'll be able to get your bf1.DataFormatString to show "29/04/2013" instead. You must first start with a datetime type column in your original SQL data source first for bf1 to properly consume it. So just add it to the data source query, and call it by a different name like CreateDate2 so as not to disturb whatever other code already depends on CreateDate, like this:

SELECT CONVERT(varchar,TableName.CreateDate,126) AS CreateDate, 
       TableName.CreateDate AS CreateDate2
FROM TableName ...

Then, in your code, you'll have to bind bf1 to "CreateDate2" instead of the original "CreateDate", like so:

BoundField bf1 = new BoundField();
bf1.DataField = "CreateDate2";
bf1.DataFormatString = "{0:dd/MM/yyyy}";
bf1.HtmlEncode = false;
bf1.HeaderText = "Sample Header 2";

dv.Fields.Add(bf1);

Voila! Your date should now show "29/04/2013" instead!

How to create a function in a cshtml template?

If your method doesn't have to return html and has to do something else then you can use a lambda instead of helper method in Razor

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";

    Func<int,int,int> Sum = (a, b) => a + b;
}

<h2>Index</h2>

@Sum(3,4)

need to test if sql query was successful

You can use this to check if there are any results ($result) from a query:

if (mysqli_num_rows($result) != 0)
 {
  //results found
 } else {
  // results not found
 }

Git adding files to repo

After adding files to the stage, you need to commit them with git commit -m "comment" after git add .. Finally, to push them to a remote repository, you need to git push <remote_repo> <local_branch>.

What REALLY happens when you don't free after malloc?

If a program forgets to free a few Megabytes before it exits the operating system will free them. But if your program runs for weeks at a time and a loop inside the program forgets to free a few bytes in each iteration you will have a mighty memory leak that will eat up all the available memory in your computer unless you reboot it on a regular basis => even small memory leaks might be bad if the program is used for a seriously big task even if it originally wasn't designed for one.

Is an HTTPS query string secure?

SSL first connects to the host, so the host name and port number are transferred as clear text. When the host responds and the challenge succeeds, the client will encrypt the HTTP request with the actual URL (i.e. anything after the third slash) and and send it to the server.

There are several ways to break this security.

It is possible to configure a proxy to act as a "man in the middle". Basically, the browser sends the request to connect to the real server to the proxy. If the proxy is configured this way, it will connect via SSL to the real server but the browser will still talk to the proxy. So if an attacker can gain access of the proxy, he can see all the data that flows through it in clear text.

Your requests will also be visible in the browser history. Users might be tempted to bookmark the site. Some users have bookmark sync tools installed, so the password could end up on deli.ci.us or some other place.

Lastly, someone might have hacked your computer and installed a keyboard logger or a screen scraper (and a lot of Trojan Horse type viruses do). Since the password is visible directly on the screen (as opposed to "*" in a password dialog), this is another security hole.

Conclusion: When it comes to security, always rely on the beaten path. There is just too much that you don't know, won't think of and which will break your neck.

How to remove newlines from beginning and end of a string?

Try this

function replaceNewLine(str) { 
  return str.replace(/[\n\r]/g, "");
}

How to save a figure in MATLAB from the command line?

When using the saveas function the resolution isn't as good as when manually saving the figure with File-->Save As..., It's more recommended to use hgexport instead, as follows:

hgexport(gcf, 'figure1.jpg', hgexport('factorystyle'), 'Format', 'jpeg');

This will do exactly as manually saving the figure.

source: http://www.mathworks.com/support/solutions/en/data/1-1PT49C/index.html?product=SL&solution=1-1PT49C

How to git clone a specific tag

git clone --depth 1 --branch <tag_name> <repo_url>

Example

git clone --depth 1 --branch 0.37.2 https://github.com/apache/incubator-superset.git

<tag_name> : 0.37.2

<repo_url> : https://github.com/apache/incubator-superset.git

How to tell if node.js is installed or not

open a terminal and enter

node -v

this will tell you the version of the nodejs installed, then run nodejs simple by entering

node

Prompt must be change. Enter following,

function testNode() {return "Node is working"}; testNode();

command line must prompt the following output if the installation was successful

'Node is working'

how to add key value pair in the JSON object already declared

you can do try lodash

Example code for json object:

_x000D_
_x000D_
    var user = {'user':'barney','age':36};
    user["newKey"] = true;
    console.log(user);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="lodash.js"></script>
_x000D_
_x000D_
_x000D_

for json array elements

Example code:

_x000D_
_x000D_
var users = [
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 }
];

users.map(i=>{i["newKey"] = true});

console.log(users);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="lodash.js"></script>
_x000D_
_x000D_
_x000D_

how to create 100% vertical line in css

I've used min-height: 100vh; with great success on some of my projects. See example.

MySql sum elements of a column

 select sum(A),sum(B),sum(C) from mytable where id in (1,2,3);

How to check if array is not empty?

print(len(a_list))

As many languages have the len() function, in Python this would work for your question.

If the output is not 0, the list is not empty.

How do I invoke a Java method when given the method name as a string?

Please refer following code may help you.

public static Method method[];
public static MethodClass obj;
public static String testMethod="A";

public static void main(String args[]) 
{
    obj=new MethodClass();
    method=obj.getClass().getMethods();
    try
    {
        for(int i=0;i<method.length;i++)
        {
            String name=method[i].getName();
            if(name==testMethod)
            {   
                method[i].invoke(name,"Test Parameters of A");
            }
        }
    }
    catch(Exception ex)
    {
        System.out.println(ex.getMessage());
    }
}

Thanks....

How do I exit a foreach loop in C#?

Just use the statement:

break;

Select columns in PySpark dataframe

Try something like this:

df.select([c for c in df.columns if c in ['_2','_4','_5']]).show()

Debugging in Maven?

I use the MAVEN_OPTS option, and find it useful to set suspend to "suspend=y" as my exec:java programs tend to be small generators which are finished before I have manage to attach a debugger.... :) With suspend on it will wait for a debugger to attach before proceding.

round value to 2 decimals javascript

If you want it visually formatted to two decimals as a string (for output) use toFixed():

var priceString = someValue.toFixed(2);

The answer by @David has two problems:

  1. It leaves the result as a floating point number, and consequently holds the possibility of displaying a particular result with many decimal places, e.g. 134.1999999999 instead of "134.20".

  2. If your value is an integer or rounds to one tenth, you will not see the additional decimal value:

    var n = 1.099;
    (Math.round( n * 100 )/100 ).toString() //-> "1.1"
    n.toFixed(2)                            //-> "1.10"
    
    var n = 3;
    (Math.round( n * 100 )/100 ).toString() //-> "3"
    n.toFixed(2)                            //-> "3.00"
    

And, as you can see above, using toFixed() is also far easier to type. ;)

Django - makemigrations - No changes detected

I know this is an old question but I fought with this same issue all day and my solution was a simple one.

I had my directory structure something along the lines of...

apps/
   app/
      __init__.py
      app_sub1/
           __init__.py
           models.py
      app_sub2/
           __init__.py
           models.py
      app_sub3/
           __init__.py
           models.py
   app2/
      __init__.py
      app2_sub1/
           __init__.py
           models.py
      app2_sub2/
           __init__.py
           models.py
      app2_sub3/
           __init__.py
           models.py
    main_app/
      __init__.py
      models.py

And since all the other models up until the one I had a problem with were being imported somewhere else that ended up importing from main_app which was registered in the INSTALLED_APPS, I just got lucky that they all worked.

But since I only added each app to INSTALLED_APPS and not the app_sub* when I finally added a new models file that wasn't imported ANYWHERE else, Django totally ignored it.

My fix was adding a models.py file to the base directory of each app like this...

apps/
   app/
      __init__.py
      models.py <<<<<<<<<<--------------------------
      app_sub1/
           __init__.py
           models.py
      app_sub2/
           __init__.py
           models.py
      app_sub3/
           __init__.py
           models.py
   app2/
      __init__.py
      models.py <<<<<<<<<<--------------------------
      app2_sub1/
           __init__.py
           models.py
      app2_sub2/
           __init__.py
           models.py
      app2_sub3/
           __init__.py
           models.py
    main_app/
      __init__.py
      models.py

and then add from apps.app.app_sub1 import * and so on to each of the app level models.py files.

Bleh... this took me SO long to figure out and I couldn't find the solution anywhere... I even went to page 2 of the google results.

Hope this helps someone!

What are libtool's .la file for?

I found very good explanation about .la files here http://openbooks.sourceforge.net/books/wga/dealing-with-libraries.html

Summary (The way I understood): Because libtool deals with static and dynamic libraries internally (through --diable-shared or --disable-static) it creates a wrapper on the library files it builds. They are treated as binary library files with in libtool supported environment.

urllib2.HTTPError: HTTP Error 403: Forbidden

NSE website has changed and the older scripts are semi-optimum to current website. This snippet can gather daily details of security. Details include symbol, security type, previous close, open price, high price, low price, average price, traded quantity, turnover, number of trades, deliverable quantities and ratio of delivered vs traded in percentage. These conveniently presented as list of dictionary form.

Python 3.X version with requests and BeautifulSoup

from requests import get
from csv import DictReader
from bs4 import BeautifulSoup as Soup
from datetime import date
from io import StringIO 

SECURITY_NAME="3MINDIA" # Change this to get quote for another stock
START_DATE= date(2017, 1, 1) # Start date of stock quote data DD-MM-YYYY
END_DATE= date(2017, 9, 14)  # End date of stock quote data DD-MM-YYYY


BASE_URL = "https://www.nseindia.com/products/dynaContent/common/productsSymbolMapping.jsp?symbol={security}&segmentLink=3&symbolCount=1&series=ALL&dateRange=+&fromDate={start_date}&toDate={end_date}&dataType=PRICEVOLUMEDELIVERABLE"




def getquote(symbol, start, end):
    start = start.strftime("%-d-%-m-%Y")
    end = end.strftime("%-d-%-m-%Y")

    hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
         'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
         'Referer': 'https://cssspritegenerator.com',
         'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
         'Accept-Encoding': 'none',
         'Accept-Language': 'en-US,en;q=0.8',
         'Connection': 'keep-alive'}

    url = BASE_URL.format(security=symbol, start_date=start, end_date=end)
    d = get(url, headers=hdr)
    soup = Soup(d.content, 'html.parser')
    payload = soup.find('div', {'id': 'csvContentDiv'}).text.replace(':', '\n')
    csv = DictReader(StringIO(payload))
    for row in csv:
        print({k:v.strip() for k, v in row.items()})


 if __name__ == '__main__':
     getquote(SECURITY_NAME, START_DATE, END_DATE)

Besides this is relatively modular and ready to use snippet.

Reading a List from properties file and load with spring annotation @Value

If you are using Spring Boot 2, it works as is, without any additional configuration.

my.list.of.strings=ABC,CDE,EFG

@Value("${my.list.of.strings}")
private List<String> myList;

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

How do I add 24 hours to a unix timestamp in php?

As you have said if you want to add 24 hours to the timestamp for right now then simply you can do:

 <?php echo strtotime('+1 day'); ?>

Above code will add 1 day or 24 hours to your current timestamp.

in place of +1 day you can take whatever you want, As php manual says strtotime can Parse about any English textual datetime description into a Unix timestamp.

examples from the manual are as below:

<?php
     echo strtotime("now"), "\n";
     echo strtotime("10 September 2000"), "\n";
     echo strtotime("+1 day"), "\n";
     echo strtotime("+1 week"), "\n";
     echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
     echo strtotime("next Thursday"), "\n";
     echo strtotime("last Monday"), "\n";
?>

Parsing a JSON array using Json.Net

You can get at the data values like this:

string json = @"
[ 
    { ""General"" : ""At this time we do not have any frequent support requests."" },
    { ""Support"" : ""For support inquires, please see our support page."" }
]";

JArray a = JArray.Parse(json);

foreach (JObject o in a.Children<JObject>())
{
    foreach (JProperty p in o.Properties())
    {
        string name = p.Name;
        string value = (string)p.Value;
        Console.WriteLine(name + " -- " + value);
    }
}

Fiddle: https://dotnetfiddle.net/uox4Vt

Inserting HTML elements with JavaScript

You want this

document.body.insertAdjacentHTML( 'afterbegin', '<div id="myID">...</div>' );

How to extract a string between two delimiters

  String s = "ABC[This is to extract]";

    System.out.println(s);
    int startIndex = s.indexOf('[');
    System.out.println("indexOf([) = " + startIndex);
    int endIndex = s.indexOf(']');
    System.out.println("indexOf(]) = " + endIndex);
    System.out.println(s.substring(startIndex + 1, endIndex));

Eclipse error ... cannot be resolved to a type

Solution : 1.Project -> Build Path -> Configure Build Path

2.Select Java Build path on the left menu, and select "Source"

3.Under Project select Include(All) and click OK

Cause : The issue might because u might have deleted the CLASS files or dependencies on the project

How can I render HTML from another file in a React component?

You could do it if template is a react component.

Template.js

var React = require('react');

var Template = React.createClass({
    render: function(){
        return (<div>Mi HTML</div>);
    }
});

module.exports = Template;

MainComponent.js

var React = require('react');
var ReactDOM = require('react-dom');
var injectTapEventPlugin = require("react-tap-event-plugin");
var Template = require('./Template');

//Needed for React Developer Tools
window.React = React;

//Needed for onTouchTap
//Can go away when react 1.0 release
//Check this repo:
//https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();

var MainComponent = React.createClass({
    render: function() {
        return(
            <Template/>
        );
    }
});

// Render the main app react component into the app div.
// For more details see: https://facebook.github.io/react/docs/top-level-api.html#react.render
ReactDOM.render(
  <MainComponent />,
  document.getElementById('app')
 );

And if you are using Material-UI, for compatibility use Material-UI Components, no normal inputs.

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app

I had the same issue running it in my pipeline.

For me, the issue was that I was using node version v10.0.0 in my docker container.

Updating it to v14.7.0 solved it for me

Warning: X may be used uninitialized in this function

one has not been assigned so points to an unpredictable location. You should either place it on the stack:

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

or dynamically allocate memory for it:

Vector* one = malloc(sizeof(*one))
one->a = 12;
one->b = 13;
one->c = -11
free(one);

Note the use of free in this case. In general, you'll need exactly one call to free for each call made to malloc.

Delete last commit in bitbucket

Once changes has been committed it will not be able to delete. because commit's basic nature is not to delete.

Thing you can do (easy and safe method),

Interactive Rebase:

1) git rebase -i HEAD~2 #will show your recent 2 commits

2) Your commit will list like , Recent will appear at the bottom of the page LILO(last in Last Out)

enter image description here

Delete the last commit row entirely

3) save it by ctrl+X or ESC:wq

now your branch will updated without your last commit..

Failed to build gem native extension (installing Compass)

I struggled with you same issue for about 3 hours. As of Compass 1.0.alpha19, the requirement is for the rvm version 1.9.3.

There are several uncollected posts, however what worked for me was the following:

  1. sudo gem uninstall sass
  2. sudo gem uninstall compass
  3. rvm install ruby-1.9.3-p448
  4. sudo gem install sass --pre
  5. sudo gem install compass --pre

and that did it. Hope it works for you as well!

Generate a random letter in Python

well, this is my answer! It works well. Just put the number of random letters you want in 'number'... (Python 3)

import random

def key_gen():
    keylist = random.choice('abcdefghijklmnopqrstuvwxyz')
    return keylist

number = 0
list_item = ''
while number < 20:
    number = number + 1
    list_item = list_item + key_gen()

print(list_item)

How to check if a query string value is present via JavaScript?

The plain javascript code sample which answers your question literally:

return location.search.indexOf('q=')>=0;

The plain javascript code sample which attempts to find if the q parameter exists and if it has a value:

var queryString=location.search;
var params=queryString.substring(1).split('&');
for(var i=0; i<params.length; i++){
    var pair=params[i].split('=');
    if(decodeURIComponent(pair[0])=='q' && pair[1])
        return true;
}
return false;

Pandas aggregate count distinct

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

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

How do I POST urlencoded form data with $http without jQuery?

All of these look like overkill (or don't work)... just do this:

$http.post(loginUrl, `username=${ encodeURIComponent(username) }` +
                     `&password=${ encodeURIComponent(password) }` +
                     '&grant_type=password'
).success(function (data) {

How can I resize an image dynamically with CSS as the browser width/height changes?

2018 and later solution:

Using viewport-relative units should make your life way easier, given we have the image of a cat:

cat

Now we want this cat inside our code, while respecting aspect ratios:

_x000D_
_x000D_
img {_x000D_
  width: 100%;_x000D_
  height: auto;_x000D_
}
_x000D_
<img src="https://www.petmd.com/sites/default/files/petmd-cat-happy-10.jpg" alt="cat">
_x000D_
_x000D_
_x000D_

So far not really interesting, but what if we would like to change the cats width to be the maximum of 50% of the viewport?

_x000D_
_x000D_
img {_x000D_
  width: 100%;_x000D_
  height: auto;_x000D_
  /* Magic! */_x000D_
  max-width: 50vw;_x000D_
}
_x000D_
<img src="https://www.petmd.com/sites/default/files/petmd-cat-happy-10.jpg" alt="cat">
_x000D_
_x000D_
_x000D_

The same image, but now restricted to a maximum width of 50vw vw (=viewport width) means the image will be X width of the viewport, depending on the digit provided. This also works for height:

_x000D_
_x000D_
img {_x000D_
  width: auto;_x000D_
  height: 100%;_x000D_
  max-height: 20vh;_x000D_
}
_x000D_
<img src="https://www.petmd.com/sites/default/files/petmd-cat-happy-10.jpg" alt="cat">
_x000D_
_x000D_
_x000D_

This restricts the height of the image to a maximum of 20% of the viewport.

How to keep the spaces at the end and/or at the beginning of a String?

Working well I'm using \u0020

<string name="hi"> Hi \u0020 </string>
<string name="ten"> \u0020 out of 10  </string>
<string name="youHaveScored">\u0020 you have Scored \u0020</string>

Java file

String finalScore = getString(R.string.hi) +name+ getString(R.string.youHaveScored)+score+ getString(R.string.ten);
               Toast.makeText(getApplicationContext(),finalScore,Toast.LENGTH_LONG).show();

Screenshot here Image of Showing Working of this code

Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

"All I want to do is join the tables and then group all the employees in a particular location together."

It sounds like what you want is for the output of the SQL statement to list every employee in the company, but first all the people in the Anaheim office, then the people in the Buffalo office, then the people in the Cleveland office (A, B, C, get it, obviously I don't know what locations you have).

In that case, lose the GROUP BY statement. All you need is ORDER BY loc.LocationID

How to get xdebug var_dump to show full object/array

These are configurable variables in php.ini:

; with sane limits
xdebug.var_display_max_depth = 10
xdebug.var_display_max_children = 256
xdebug.var_display_max_data = 1024 


; with no limits
; (maximum nesting is 1023)
xdebug.var_display_max_depth = -1 
xdebug.var_display_max_children = -1
xdebug.var_display_max_data = -1 

Of course, these may also be set at runtime via ini_set(), useful if you don't want to modify php.ini and restart your web server but need to quickly inspect something more deeply.

ini_set('xdebug.var_display_max_depth', '10');
ini_set('xdebug.var_display_max_children', '256');
ini_set('xdebug.var_display_max_data', '1024');

Xdebug settings are explained in the official documentation.

Can I extend a class using more than 1 class in PHP?

EDIT: 2020 PHP 5.4+ and 7+

As of PHP 5.4.0 there are "Traits" - you can use more traits in one class, so the final deciding point would be whether you want really an inheritance or you just need some "feature"(trait). Trait is, vaguely said, an already implemented interface that is meant to be just used.


Currently accepted answer by @Franck will work but it is not in fact multiple inheritance but a child instance of class defined out of scope, also there is the `__call()` shorthand - consider using just `$this->childInstance->method(args)` anywhere you need ExternalClass class method in "extended" class.

Exact answer

No you can't, respectively, not really, as manual of extends keyword says:

An extended class is always dependent on a single base class, that is, multiple inheritance is not supported.

Real answer

However as @adam suggested correctly this does NOT forbids you to use multiple hierarchal inheritance.

You CAN extend one class, with another and another with another and so on...

So pretty simple example on this would be:

class firstInheritance{}
class secondInheritance extends firstInheritance{}
class someFinalClass extends secondInheritance{}
//...and so on...

Important note

As you might have noticed, you can only do multiple(2+) intehritance by hierarchy if you have control over all classes included in the process - that means, you can't apply this solution e.g. with built-in classes or with classes you simply can't edit - if you want to do that, you are left with the @Franck solution - child instances.

...And finally example with some output:

class A{
  function a_hi(){
    echo "I am a of A".PHP_EOL."<br>".PHP_EOL;  
  }
}

class B extends A{
  function b_hi(){
    echo "I am b of B".PHP_EOL."<br>".PHP_EOL;  
  }
}

class C extends B{
  function c_hi(){
    echo "I am c of C".PHP_EOL."<br>".PHP_EOL;  
  }
}

$myTestInstance = new C();

$myTestInstance->a_hi();
$myTestInstance->b_hi();
$myTestInstance->c_hi();

Which outputs

I am a of A 
I am b of B 
I am c of C 

TypeScript for ... of with index / key?

You can use the for..in TypeScript operator to access the index when dealing with collections.

var test = [7,8,9];
for (var i in test) {
   console.log(i + ': ' + test[i]);
} 

Output:

 0: 7
 1: 8
 2: 9

See Demo

How to install Python package from GitHub?

To install Python package from github, you need to clone that repository.

git clone https://github.com/jkbr/httpie.git

Then just run the setup.py file from that directory,

sudo python setup.py install

HQL Hibernate INNER JOIN

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="empTable")
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String empName;

List<Address> addList=new ArrayList<Address>();


@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="emp_id")
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getEmpName() {
    return empName;
}
public void setEmpName(String empName) {
    this.empName = empName;
}

@OneToMany(mappedBy="employee",cascade=CascadeType.ALL)
public List<Address> getAddList() {
    return addList;
}

public void setAddList(List<Address> addList) {
    this.addList = addList;
}
}

We have two entities Employee and Address with One to Many relationship.

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="address")
public class Address implements Serializable{

private static final long serialVersionUID = 1L;

private int address_id;
private String address;
Employee employee;

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getAddress_id() {
    return address_id;
}
public void setAddress_id(int address_id) {
    this.address_id = address_id;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}

@ManyToOne
@JoinColumn(name="emp_id")
public Employee getEmployee() {
    return employee;
}
public void setEmployee(Employee employee) {
    this.employee = employee;
}
}

By this way we can implement inner join between two tables

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;

public class Main {

public static void main(String[] args) {
    saveEmployee();

    retrieveEmployee();

}

private static void saveEmployee() {
    Employee employee=new Employee();
    Employee employee1=new Employee();
    Employee employee2=new Employee();
    Employee employee3=new Employee();

    Address address=new Address();
    Address address1=new Address();
    Address address2=new Address();
    Address address3=new Address();

    address.setAddress("1485,Sector 42 b");
    address1.setAddress("1485,Sector 42 c");
    address2.setAddress("1485,Sector 42 d");
    address3.setAddress("1485,Sector 42 a");

    employee.setEmpName("Varun");
    employee1.setEmpName("Krishan");
    employee2.setEmpName("Aasif");
    employee3.setEmpName("Dut");

    address.setEmployee(employee);
    address1.setEmployee(employee1);
    address2.setEmployee(employee2);
    address3.setEmployee(employee3);

    employee.getAddList().add(address);
    employee1.getAddList().add(address1);
    employee2.getAddList().add(address2);
    employee3.getAddList().add(address3);

    Session session=HibernateUtil.getSessionFactory().openSession();

    session.beginTransaction();

    session.save(employee);
    session.save(employee1);
    session.save(employee2);
    session.save(employee3);
    session.getTransaction().commit();
    session.close();
}

private static void retrieveEmployee() {
    try{

    String sqlQuery="select e from Employee e inner join e.addList";

    Session session=HibernateUtil.getSessionFactory().openSession();

    Query query=session.createQuery(sqlQuery);

    List<Employee> list=query.list();

     list.stream().forEach((p)->{System.out.println(p.getEmpName());});     
    session.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}
}

I have used Java 8 for loop for priting the names. Make sure you have jdk 1.8 with tomcat 8. Also add some more records for better understanding.

 public class HibernateUtil {
 private static SessionFactory sessionFactory ;
 static {
    Configuration configuration = new Configuration();

    configuration.addAnnotatedClass(Employee.class);
    configuration.addAnnotatedClass(Address.class);
                  configuration.setProperty("connection.driver_class","com.mysql.jdbc.Driver");
    configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");                                
    configuration.setProperty("hibernate.connection.username", "root");     
    configuration.setProperty("hibernate.connection.password", "root");
    configuration.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
    configuration.setProperty("hibernate.hbm2ddl.auto", "update");
    configuration.setProperty("hibernate.show_sql", "true");
    configuration.setProperty(" hibernate.connection.pool_size", "10");


   // configuration
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    sessionFactory = configuration.buildSessionFactory(builder.build());
 }
public static SessionFactory getSessionFactory() {
    return sessionFactory;
}
} 

In Tkinter is there any way to make a widget not visible?

I'm also extremely late to the party, but I'll leave my version of the answer here for others who may have gotten here, like I did, searching for how to hide something that was placed on the screen with the .place() function, and not .pack() neither .grid().

In short, you can hide a widget by setting the width and height to zero, like this:

widget.place(anchor="nw", x=0, y=0, width=0, height=0)

To give a bit of context so you can see what my requirement was and how I got here. In my program, I have a window that needs to display several things that I've organized into 2 frames, something like this:

[WINDOW - app]
  [FRAME 1 - hMainWndFrame]
    [Buttons and other controls (widgets)]
  [FRAME 2 - hJTensWndFrame]
    [other Buttons and controls (widgets)]

Only one frame needs to be visible at a time, so on application initialisation, i have something like this:

hMainWndFrame = Frame(app, bg="#aababd")
hMainWndFrame.place(anchor="nw", x=0, y=0, width=480, height=320)
...
hJTensWndFrame = Frame(app, bg="#aababd")

I'm using .place() instead of .pack() or .grid() because i specifically want to set precise coordinates on the window for each widget. So, when i want to hide the main frame and display the other one (along with all the other controls), all i have to do is call the .place() function again, on each frame, but specifying zero for width and height for the one i want to hide and the necessary width and height for the one i want to show, such as:

hMainWndFrame.place(anchor="nw", x=0, y=0, width=0, height=0)
hJTensWndFrame.place(anchor="nw", x=0, y=0, width=480, height=320)

Now it's true, I only tested this on Frames, not on other widgets, but I guess it should work on everything.

C# - Fill a combo box with a DataTable

A few points:

1) "DataBind()" is only for web apps (not windows apps).

2) Your code looks very 'JAVAish' (not a bad thing, just an observation).

Try this:

mnuActionLanguage.ComboBox.DataSource = languages;

If that doesn't work... then I'm assuming that your datasource is being stepped on somewhere else in the code.

How to convert an Instant to a date format?

If you want to convert an Instant to a Date:

Date myDate = Date.from(instant);

And then you can use SimpleDateFormat for the formatting part of your question:

SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
String formattedDate = formatter.format(myDate);

Difference between "and" and && in Ruby?

|| and && bind with the precedence that you expect from boolean operators in programming languages (&& is very strong, || is slightly less strong).

and and or have lower precedence.

For example, unlike ||, or has lower precedence than =:

> a = false || true
 => true 
> a
 => true 
> a = false or true
 => true 
> a
 => false

Likewise, unlike &&, and also has lower precedence than =:

> a = true && false
 => false 
> a
 => false 
> a = true and false
 => false 
> a
 => true 

What's more, unlike && and ||, and and or bind with equal precedence:

> !puts(1) || !puts(2) && !puts(3)
1
 => true
> !puts(1) or !puts(2) and !puts(3)
1
3
 => true 
> !puts(1) or (!puts(2) and !puts(3))
1
 => true

The weakly-binding and and or may be useful for control-flow purposes: see http://devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby/ .

HTML page disable copy/paste

You cannot prevent people from copying text from your page. If you are trying to satisfy a "requirement" this may work for you:

<body oncopy="return false" oncut="return false" onpaste="return false">

How to disable Ctrl C/V using javascript for both internet explorer and firefox browsers

A more advanced aproach:

How to detect Ctrl+V, Ctrl+C using JavaScript?

Edit: I just want to emphasise that disabling copy/paste is annoying, won't prevent copying and is 99% likely a bad idea.

Delete duplicate elements from an array

Try following from Removing duplicates from an Array(simple):

Array.prototype.removeDuplicates = function (){
  var temp=new Array();
  this.sort();
  for(i=0;i<this.length;i++){
    if(this[i]==this[i+1]) {continue}
    temp[temp.length]=this[i];
  }
  return temp;
} 

Edit:

This code doesn't need sort:

Array.prototype.removeDuplicates = function (){
  var temp=new Array();
  label:for(i=0;i<this.length;i++){
        for(var j=0; j<temp.length;j++ ){//check duplicates
            if(temp[j]==this[i])//skip if already present 
               continue label;      
        }
        temp[temp.length] = this[i];
  }
  return temp;
 } 

(But not a tested code!)

Multi-statement Table Valued Function vs Inline Table Valued Function

Internally, SQL Server treats an inline table valued function much like it would a view and treats a multi-statement table valued function similar to how it would a stored procedure.

When an inline table-valued function is used as part of an outer query, the query processor expands the UDF definition and generates an execution plan that accesses the underlying objects, using the indexes on these objects.

For a multi-statement table valued function, an execution plan is created for the function itself and stored in the execution plan cache (once the function has been executed the first time). If multi-statement table valued functions are used as part of larger queries then the optimiser does not know what the function returns, and so makes some standard assumptions - in effect it assumes that the function will return a single row, and that the returns of the function will be accessed by using a table scan against a table with a single row.

Where multi-statement table valued functions can perform poorly is when they return a large number of rows and are joined against in outer queries. The performance issues are primarily down to the fact that the optimiser will produce a plan assuming that a single row is returned, which will not necessarily be the most appropriate plan.

As a general rule of thumb we have found that where possible inline table valued functions should be used in preference to multi-statement ones (when the UDF will be used as part of an outer query) due to these potential performance issues.

How to force ViewPager to re-instantiate its items

Had the same problem. For me it worked to call

viewPage.setAdapter( adapter );

again which caused reinstantiating the pages again.

Adding a default value in dropdownlist after binding with database

After data-binding, do this:

ddlColor.Items.Insert(0, new ListItem("Select","NA")); //updated code

Or follow Brian's second suggestion if you want to do it in markup.

You should probably add a RequiredFieldValidator control and set its InitialValue to "NA".

<asp:RequiredFieldValidator .. ControlToValidate="ddlColor" InitialValue="NA" />

JavaScript editor within Eclipse

Disclaimer, I work at Aptana. I would point out there are some nice features for JS that you might not get so easily elsewhere. One is plugin-level integration of JS libraries that provide CodeAssist, samples, snippets and easy inclusion of the libraries files into your project; we provide the plugins for many of the more commonly used libraries, including YUI, jQuery, Prototype, dojo and EXT JS.

Second, we have a server-side JavaScript engine called Jaxer that not only lets you run any of your JS code on the server but adds file, database and networking functionality so that you don't have to use a scripting language but can write the entire app in JS.

Is the sizeof(some pointer) always equal to four?

The reason the size of your pointer is 4 bytes is because you are compiling for a 32-bit architecture. As FryGuy pointed out, on a 64-bit architecture you would see 8.

How do you round a floating point number in Perl?

cat table |
  perl -ne '/\d+\s+(\d+)\s+(\S+)/ && print "".**int**(log($1)/log(2))."\t$2\n";' 

Close dialog on click (anywhere)

Try this:

$(".ui-widget-overlay").click(function () {
    $(".ui-icon.ui-icon-closethick").trigger("click");
}); 

Set form backcolor to custom color

With Winforms you can use Form.BackColor to do this.
From within the Form's code:

BackColor = Color.LightPink;

If you mean a WPF Window you can use the Background property.
From within the Window's code:

Background = Brushes.LightPink;

syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

I stumbled on this question as I had the same error. Mine was due to a slightly different problem and since I resolved it on my own I thought it useful to share here. Original code with issue:

$comment = "$_POST['comment']";

Because of the enclosing double-quotes, the index is not dereferenced properly leading to the assignment error. In my case I chose to fix it like this:

$comment = "$_POST[comment]";

but dropping either pair of quotes works; it's a matter of style I suppose :)

Opening A Specific File With A Batch File?

@echo off
start %1

or if needed to escape the characters -

@echo off
start %%1

How do I find what Java version Tomcat6 is using?

Or you could use the Probe application and just look at its System Info page. Much easier than writing code, and once you start using it you'll never go back to Tomcat Manager.

Anaconda export Environment file

The easiest way to save the packages from an environment to be installed in another computer is:

$ conda list -e > req.txt

then you can install the environment using

$ conda create -n <environment-name> --file req.txt

if you use pip, please use the following commands: reference https://pip.pypa.io/en/stable/reference/pip_freeze/

$ env1/bin/pip freeze > requirements.txt
$ env2/bin/pip install -r requirements.txt

The required anti-forgery form field "__RequestVerificationToken" is not present Error in user Registration

In my case it was due to adding requireSSL=true to httpcookies in webconfig which made the AntiForgeryToken stop working. Example:

<system.web>
  <httpCookies httpOnlyCookies="true" requireSSL="true"/>
</system.web>

To make both requireSSL=true and @Html.AntiForgeryToken() work I added this line inside the Application_BeginRequest in Global.asax

    protected void Application_BeginRequest(object sender, EventArgs e)
  {
    AntiForgeryConfig.RequireSsl = HttpContext.Current.Request.IsSecureConnection;
  }

Create hive table using "as select" or "like" and also specify delimiter

Let's say we have an external table called employee

hive> SHOW CREATE TABLE employee;
OK
CREATE EXTERNAL TABLE employee(
  id string,
  fname string,
  lname string, 
  salary double)
ROW FORMAT SERDE
  'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'
WITH SERDEPROPERTIES (
  'colelction.delim'=':',
  'field.delim'=',',
  'line.delim'='\n',
  'serialization.format'=',')
STORED AS INPUTFORMAT
  'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
  'maprfs:/user/hadoop/data/employee'
TBLPROPERTIES (
  'COLUMN_STATS_ACCURATE'='false',
  'numFiles'='0',
  'numRows'='-1',
  'rawDataSize'='-1',
  'totalSize'='0',
  'transient_lastDdlTime'='1487884795')
  1. To create a person table like employee

    CREATE TABLE person LIKE employee;

  2. To create a person external table like employee

    CREATE TABLE person LIKE employee LOCATION 'maprfs:/user/hadoop/data/person';

  3. then use DESC person; to see the newly created table schema.

Command not found after npm install in zsh

I think the problem is more about the ZSH completion.

You need to add this line in your .zshrc:

zstyle ':completion:*' rehash true

If you have Oh-my-zsh, a PR has been made, you can integrate it until it is pulled: https://github.com/robbyrussell/oh-my-zsh/issues/3440

SQL Server - In clause with a declared variable

I have another solution to do it without dynamic query. We can do it with the help of xquery as well.

    SET @Xml = cast(('<A>'+replace('3,4,22,6014',',' ,'</A><A>')+'</A>') AS XML)
    Select @Xml

    SELECT A.value('.', 'varchar(max)') as [Column] FROM @Xml.nodes('A') AS FN(A)

Here is the complete solution : http://raresql.com/2011/12/21/how-to-use-multiple-values-for-in-clause-using-same-parameter-sql-server/

Git Cherry-pick vs Merge Workflow

Rebase and Cherry-pick is the only way you can keep clean commit history. Avoid using merge and avoid creating merge conflict. If you are using gerrit set one project to Merge if necessary and one project to cherry-pick mode and try yourself.

How do I get hour and minutes from NSDate?

This seems to me to be what the question is after, no need for formatters:

NSDate *date = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];

What is the difference between static func and class func in Swift?

To declare a type variable property, mark the declaration with the static declaration modifier. Classes may mark type computed properties with the class declaration modifier instead to allow subclasses to override the superclass’s implementation. Type properties are discussed in Type Properties.

NOTE
In a class declaration, the keyword static has the same effect as marking the declaration with both the class and final declaration modifiers.

Source: The Swift Programming Language - Type Variable Properties

How do I programmatically set the value of a select box element using JavaScript?

function setSelectValue (id, val) {
    document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);

How to install a Mac application using Terminal

To disable inputting password:

sudo visudo

Then add a new line like below and save then:

# The user can run installer as root without inputting password
yourusername ALL=(root) NOPASSWD: /usr/sbin/installer

Then you run installer without password:

sudo installer -pkg ...