Programs & Examples On #Html2pdf

HTML2PDF is a HTML to PDF converter written in PHP4 (use FPDF), and PHP5 (use TCPDF). It allows the conversion of valid HTML 4.01 in PDF format. It's an open source project since 2015, the source is hosted on github [(link)](https://github.com/spipu/html2pdf/)

How to properly use jsPDF library

you can use pdf from html as follows,

Step 1: Add the following script to the header

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>

or download locally

Step 2: Add HTML script to execute jsPDF code

Customize this to pass the identifier or just change #content to be the identifier you need.

 <script>
    function demoFromHTML() {
        var pdf = new jsPDF('p', 'pt', 'letter');
        // source can be HTML-formatted string, or a reference
        // to an actual DOM element from which the text will be scraped.
        source = $('#content')[0];

        // we support special element handlers. Register them with jQuery-style 
        // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
        // There is no support for any other type of selectors 
        // (class, of compound) at this time.
        specialElementHandlers = {
            // element with id of "bypass" - jQuery style selector
            '#bypassme': function (element, renderer) {
                // true = "handled elsewhere, bypass text extraction"
                return true
            }
        };
        margins = {
            top: 80,
            bottom: 60,
            left: 40,
            width: 522
        };
        // all coords and widths are in jsPDF instance's declared units
        // 'inches' in this case
        pdf.fromHTML(
            source, // HTML string or DOM elem ref.
            margins.left, // x coord
            margins.top, { // y coord
                'width': margins.width, // max width of content on PDF
                'elementHandlers': specialElementHandlers
            },

            function (dispose) {
                // dispose: object with X, Y of the last line add to the PDF 
                //          this allow the insertion of new lines after html
                pdf.save('Test.pdf');
            }, margins
        );
    }
</script>

Step 3: Add your body content

<a href="javascript:demoFromHTML()" class="button">Run Code</a>
<div id="content">
    <h1>  
        We support special element handlers. Register them with jQuery-style.
    </h1>
</div>

Refer to the original tutorial

See a working fiddle

How to position text over an image in css

as of 2017 this is more responsive and worked for me. This is for putting text inside vs over, like a badge. instead of the number 8, I had a variable to pull data from a database.

this code started with Kailas's answer up above

https://jsfiddle.net/jim54729/memmu2wb/3/

My HTML

<div class="containerBox">
  <img class="img-responsive"    src="https://s20.postimg.org/huun8e6fh/Gold_Ring.png">
  <div class='text-box'>
   <p class='dataNumber'> 8 </p>
  </div>
</div>

and my css:

.containerBox {
  position: relative;
  display: inline-block;
}

.text-box {
  position: absolute;
  height: 30%;
  text-align: center;
  width: 100%;
  margin: auto;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  font-size: 30px;
}

.img-responsive {
  display: block;
  max-width: 100%;
  height: 120px;
  margin: auto;
  padding: auto;
}

.dataNumber {
  margin-top: auto;
}

Convert HTML + CSS to PDF

Fine rendering doesn't mean anything. Does it validate?

All browsers do the most they can to just show something on the screen, no matter how bad the input. And of course they do not do the same thing. If you want the same rendering as FireFox, you could use its rendering engine. There are pdf generators for it. It is an awful lot of work, though.

How exactly does binary code get converted into letters?

Here's a way to convert binary numbers to ASCII characters that is often simple enough to do in your head.

1 - Convert every 4 binary digits into one hex digit.

Here's a binary to hex conversion chart:

0001 = 1 
0010 = 2 
0011 = 3 
0100 = 4 
0101 = 5
0110 = 6
0111 = 7
1000 = 8

1001 = 9
1010 = a (the hex number a, not the letter a)
1011 = b
1100 = c
1101 = d
1110 = e
1111 = f

(The hexadecimal numbers a through f are the decimal numbers 10 through 15. That's what hexadecimal, or "base 16" is - instead of each digit being capable of representing 10 different numbers [0 - 9], like decimal or "base 10" does, each digit is instead capable of representing 16 different numbers [0 - f].)

Once you know that chart, converting any string of binary digits into a string of hex digits is simple.

For example,

01000100 = 0100 0100 = 44 hex
1010001001110011 = 1010 0010 0111 0011 = a273 hex

Simple enough, right? It is a simple matter to convert a binary number of any length into its hexadecimal equivalent.

(This works because hexadecimal is base 16 and binary is base 2 and 16 is the 4th power of 2, so it takes 4 binary digits to make 1 hex digit. 10, on the other hand, is not a power of 2, so we can't convert binary to decimal nearly as easily.)

2 - Split the string of hex digits into pairs.

When converting a number into ASCII, every 2 hex digits is a character. So break the hex string into sets of 2 digits.

You would split a hex number like 7340298b392 this into 6 pairs, like this:

7340298b392 = 07 34 02 98 b3 92

(Notice I prepended a 0, since I had an odd number of hex digits.)

That's 6 pairs of hex digits, so its going to be 6 letters. (Except I know right away that 98, b3 and 92 aren't letters. I'll explain why in a minute.)

3 - Convert each pair of hex digits into a decimal number.

Do this by multiplying the (decimal equivalent of the) left digit by 16, and adding the 2nd.

For example, b3 hex = 11*16 + 3, which is 110 + 66 + 3, which is 179. (b hex is 11 decimal.)

4 - Convert the decimal numbers into ASCII characters.

Now, to get the ASCII letters for the decimal numbers, simply keep in mind that in ASCII, 65 is an uppercase 'A', and 97 is a lowercase 'a'.

So what letter is 68?

68 is the 4th letter of the alphabet in uppercase, right?
65 = A, 66 = B, 67 = C, 68 = D.

So 68 is 'D'.

You take the decimal number, subtract 64 for uppercase letters if the number is less than 97, or 96 for lowercase letters if the number is 97 or larger, and that's the number of the letter of the alphabet associated with that set of 2 hex digits.


Alternatively, if you're not afraid of a little bit of easy hex arithmetic, you can skip step 3, and just go straight from hex to ASCII, by remembering, for example, that

hex 41 = 'A' 
hex 61 = 'a'

So subtract 40 hex for uppercase letters or 60 hex for lowercase letters, and convert what's left to decimal to get the alphabet letter number.

For example

01101100 = 6c, 6c - 60 = c = 12 decimal = 'l'
01010010 = 52, 52 - 40 = 12 hex = 18 decimal = 'R'

(When doing this, it's helpful to remember that 'm' (or 'M') is the 13 letter of the alphabet. So you can count up or down from 13 to find a letter that's nearer to the middle than to either end.)

I saw this on a shirt once, and was able to read it in my head:

01000100
01000001
01000100

I did it like this:

01000100 = 0100 0100 = 44 hex, - 40 hex = ucase letter 4 = D
01000001 = 0100 0001 = 41 hex, - 40 hex = ucase letter 1 = A
01000100 = 0100 0100 = 44 hex, - 40 hex = ucase letter 4 = D

The shirt said "DAD", which I thought was kinda cool, since it was being purchased by a pregnant woman. Her husband must be a geek like me.


How did I know right away that 92, b3, and 98 were not letters?

Because the ASCII code for a lowercase 'z' is 96 + 26 = 122, which in hex is 7a. 7a is the largest hex number for a letter. Anything larger than 7a is not a letter.


So that's how you can do it as a human.

How do computer programs do it?

For each set of 8 binary digits, convert it to a number, and look it up in an ASCII table.

(That's one pretty obvious and straight forward way. A typical programmer could probably think of 10 or 15 other ways in the space of a few minutes. The details depend on the computer language environment.)

Git: which is the default configured remote for branch?

You can do it more simply, guaranteeing that your .gitconfig is left in a meaningful state:

Using Git version v1.8.0 and above

git push -u hub master when pushing, or:
git branch -u hub/master

OR

(This will set the remote for the currently checked-out branch to hub/master)
git branch --set-upstream-to hub/master

OR

(This will set the remote for the branch named branch_name to hub/master)
git branch branch_name --set-upstream-to hub/master

If you're using v1.7.x or earlier

you must use --set-upstream:
git branch --set-upstream master hub/master

How to perform string interpolation in TypeScript?

In JavaScript you can use template literals:

let value = 100;
console.log(`The size is ${ value }`);

Python Remove last char from string and return it

Strings are "immutable" for good reason: It really saves a lot of headaches, more often than you'd think. It also allows python to be very smart about optimizing their use. If you want to process your string in increments, you can pull out part of it with split() or separate it into two parts using indices:

a = "abc"
a, result = a[:-1], a[-1]

This shows that you're splitting your string in two. If you'll be examining every byte of the string, you can iterate over it (in reverse, if you wish):

for result in reversed(a):
    ...

I should add this seems a little contrived: Your string is more likely to have some separator, and then you'll use split:

ans = "foo,blah,etc."
for a in ans.split(","):
    ...

Android - styling seek bar

If you are using default SeekBar provided by android Sdk then their is a simple way to change the color of that . just go to color.xml inside /res/values/colors.xml and change the colorAccent.

<resources>
    <color name="colorPrimary">#212121</color>
    <color name="colorPrimaryDark">#1e1d1d</color>
     <!-- change below line -->
    <color name="colorAccent">#FF4081</color>
</resources>

How to store printStackTrace into a string

StackTraceElement[] stack = new Exception().getStackTrace();
String theTrace = "";
for(StackTraceElement line : stack)
{
   theTrace += line.toString();
}

java.net.UnknownHostException: Invalid hostname for server: local

This is not specific to the question, but this question showed up when I was Googling for the mentioned UnknownHostException, and the fix is not found anywhere else so I thought I'd add an answer here.

The exception that was continuously received was:

java.net.UnknownHostException:  google.com
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at java.net.Socket.<init>(Socket.java:434)
    at java.net.Socket.<init>(Socket.java:211)
    ... 

No matter how I tried to connect to any valid host, printing it in the terminal would not help either. Everything was right.

The Solution

Not calling trim() for the host string which contained whitespace. In writing a proxy server the host was obtained from HTTP headers with the use of split(":") by semicolons for the HOST header. This left whitespace, and causes the UnknownHostException as a host with whitespace is not a valid host. Doing a host = host.trim() on the String host solved the ambiguous issue.

REST API 404: Bad URI, or Missing Resource?

For this scenario HTTP 404 is response code for the response from the REST API Like 400, 401, 404 , 422 unprocessable entity

use the Exception handling to check the full exception message.

try{
  // call the rest api
} catch(RestClientException e) {
     //process exception
     if(e instanceof HttpStatusCodeException){
        String responseText=((HttpStatusCodeException)e).getResponseBodyAsString();
         //now you have the response, construct json from it, and extract the errors
         System.out.println("Exception :" +responseText);
     }

}

This exception block give you the proper message thrown by the REST API

What is a "slug" in Django?

Slug is a newspaper term. A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs. (as in Django docs)

A slug field in Django is used to store and generate valid URLs for your dynamically created web pages.

Just like the way you added this question on Stack Overflow and a dynamic page was generated and when you see in the address bar you will see your question title with "-" in place of the spaces. That's exactly the job of a slug field.

Enter image description here

The title entered by you was something like this -> What is a “slug” in Django?

On storing it into a slug field it becomes "what-is-a-slug-in-django" (see URL of this page)

Handle spring security authentication exceptions with @ExceptionHandler

This is a very interesting problem that Spring Security and Spring Web framework is not quite consistent in the way they handle the response. I believe it has to natively support error message handling with MessageConverter in a handy way.

I tried to find an elegant way to inject MessageConverter into Spring Security so that they could catch the exception and return them in a right format according to content negotiation. Still, my solution below is not elegant but at least make use of Spring code.

I assume you know how to include Jackson and JAXB library, otherwise there is no point to proceed. There are 3 Steps in total.

Step 1 - Create a standalone class, storing MessageConverters

This class plays no magic. It simply stores the message converters and a processor RequestResponseBodyMethodProcessor. The magic is inside that processor which will do all the job including content negotiation and converting the response body accordingly.

public class MessageProcessor { // Any name you like
    // List of HttpMessageConverter
    private List<HttpMessageConverter<?>> messageConverters;
    // under org.springframework.web.servlet.mvc.method.annotation
    private RequestResponseBodyMethodProcessor processor;

    /**
     * Below class name are copied from the framework.
     * (And yes, they are hard-coded, too)
     */
    private static final boolean jaxb2Present =
        ClassUtils.isPresent("javax.xml.bind.Binder", MessageProcessor.class.getClassLoader());

    private static final boolean jackson2Present =
        ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", MessageProcessor.class.getClassLoader()) &&
        ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", MessageProcessor.class.getClassLoader());

    private static final boolean gsonPresent =
        ClassUtils.isPresent("com.google.gson.Gson", MessageProcessor.class.getClassLoader());

    public MessageProcessor() {
        this.messageConverters = new ArrayList<HttpMessageConverter<?>>();

        this.messageConverters.add(new ByteArrayHttpMessageConverter());
        this.messageConverters.add(new StringHttpMessageConverter());
        this.messageConverters.add(new ResourceHttpMessageConverter());
        this.messageConverters.add(new SourceHttpMessageConverter<Source>());
        this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());

        if (jaxb2Present) {
            this.messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
        }
        if (jackson2Present) {
            this.messageConverters.add(new MappingJackson2HttpMessageConverter());
        }
        else if (gsonPresent) {
            this.messageConverters.add(new GsonHttpMessageConverter());
        }

        processor = new RequestResponseBodyMethodProcessor(this.messageConverters);
    }

    /**
     * This method will convert the response body to the desire format.
     */
    public void handle(Object returnValue, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
        ServletWebRequest nativeRequest = new ServletWebRequest(request, response);
        processor.handleReturnValue(returnValue, null, new ModelAndViewContainer(), nativeRequest);
    }

    /**
     * @return list of message converters
     */
    public List<HttpMessageConverter<?>> getMessageConverters() {
        return messageConverters;
    }
}

Step 2 - Create AuthenticationEntryPoint

As in many tutorials, this class is essential to implement custom error handling.

public class CustomEntryPoint implements AuthenticationEntryPoint {
    // The class from Step 1
    private MessageProcessor processor;

    public CustomEntryPoint() {
        // It is up to you to decide when to instantiate
        processor = new MessageProcessor();
    }

    @Override
    public void commence(HttpServletRequest request,
        HttpServletResponse response, AuthenticationException authException)
        throws IOException, ServletException {

        // This object is just like the model class, 
        // the processor will convert it to appropriate format in response body
        CustomExceptionObject returnValue = new CustomExceptionObject();
        try {
            processor.handle(returnValue, request, response);
        } catch (Exception e) {
            throw new ServletException();
        }
    }
}

Step 3 - Register the entry point

As mentioned, I do it with Java Config. I just show the relevant configuration here, there should be other configuration such as session stateless, etc.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().authenticationEntryPoint(new CustomEntryPoint());
    }
}

Try with some authentication fail cases, remember the request header should include Accept : XXX and you should get the exception in JSON, XML or some other formats.

Global variables in AngularJS

Example of AngularJS "global variables" using $rootScope:

Controller 1 sets the global variable:

function MyCtrl1($scope, $rootScope) {
    $rootScope.name = 'anonymous'; 
}

Controller 2 reads the global variable:

function MyCtrl2($scope, $rootScope) {
    $scope.name2 = $rootScope.name; 
}

Here is a working jsFiddle: http://jsfiddle.net/natefriedman/3XT3F/1/

How to pause a YouTube player when hiding the iframe?

Here's a jQuery take on RobW's answer for use hiding /pausing an iframe in a modal window:

    function toggleVideo(state) {
        if(state == 'hide'){
            $('#video-div').modal('hide');
            document.getElementById('video-iframe'+id).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
        }
        else {
            $('#video-div').modal('show');
            document.getElementById('video-iframe'+id).contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
        }
    }

The html elements referred to are the modal div itself (#video-div) calling the show / hide methods, and the iframe (#video-iframe) which has the video url as is src="" and has the suffix enablejsapi=1? which enables programmatic control of the player (ex. .

For more on the html see RobW's answer.

how to redirect to external url from c# controller

Use the Controller's Redirect() method.

public ActionResult YourAction()
{
    // ...
    return Redirect("http://www.example.com");
}

Update

You can't directly perform a server side redirect from an ajax response. You could, however, return a JsonResult with the new url and perform the redirect with javascript.

public ActionResult YourAction()
{
    // ...
    return Json(new {url = "http://www.example.com"});
}

$.post("@Url.Action("YourAction")", function(data) {
    window.location = data.url;
});

Regex replace (in Python) - a simpler way?

>>> import re
>>> s = "start foo end"
>>> s = re.sub("foo", "replaced", s)
>>> s
'start replaced end'
>>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s)
>>> s
'start can use a callable for the replaced text too end'
>>> help(re.sub)
Help on function sub in module re:

sub(pattern, repl, string, count=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a callable, it's passed the match object and must return
    a replacement string to be used.

When should I use GET or POST method? What's the difference between them?

I use GET when I'm retrieving information from a URL and POST when I'm sending information to a URL.

Export tables to an excel spreadsheet in same directory

You can use VBA to export an Access database table as a Worksheet in an Excel Workbook.

To obtain the path of the Access database, use the CurrentProject.Path property.

To name the Excel Workbook file with the current date, use the Format(Date, "yyyyMMdd") method.

Finally, to export the table as a Worksheet, use the DoCmd.TransferSpreadsheet method.

Example:

Dim outputFileName As String
outputFileName = CurrentProject.Path & "\Export_" & Format(Date, "yyyyMMdd") & ".xls"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table1", outputFileName , True
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table2", outputFileName , True

This will output both Table1 and Table2 into the same Workbook.

HTH

Remote branch is not showing up in "git branch -r"

The remote section also specifies fetch rules. You could add something like this into it to fetch all branches from the remote:

fetch = +refs/heads/*:refs/remotes/origin/*

(Or replace origin with bitbucket.)

Please read about it here: 10.5 Git Internals - The Refspec

What's the difference between '$(this)' and 'this'?

$() is the jQuery constructor function.

this is a reference to the DOM element of invocation.

So basically, in $(this), you are just passing the this in $() as a parameter so that you could call jQuery methods and functions.

FIFO class in Java

You can use LinkedBlockingQueue I use it in my projects. It's part of standard java and quite easy to use

How to set cookies in laravel 5 independently inside controller

If you want to set cookie and get it outside of request, Laravel is not your friend.

Laravel cookies are part of Request, so if you want to do this outside of Request object, use good 'ole PHP setcookie(..) and $_COOKIE to get it.

How to initialize weights in PyTorch?

Sorry for being so late, I hope my answer will help.

To initialise weights with a normal distribution use:

torch.nn.init.normal_(tensor, mean=0, std=1)

Or to use a constant distribution write:

torch.nn.init.constant_(tensor, value)

Or to use an uniform distribution:

torch.nn.init.uniform_(tensor, a=0, b=1) # a: lower_bound, b: upper_bound

You can check other methods to initialise tensors here

How to download files using axios

Downloading Files (using Axios and Security)

This is actually even more complex when you want to download files using Axios and some means of security. To prevent anyone else from spending too much time in figuring this out, let me walk you through this.

You need to do 3 things:

1. Configure your server to permit the browser to see required HTTP headers
2. Implement the server-side service, and making it advertise the correct file type for the downloaded file.
3. Implementing an Axios handler to trigger a FileDownload dialog within the browser

These steps are mostly doable - but are complicated considerably by the browser's relation to CORS. One step at a time:

1. Configure your (HTTP) server

When employing transport security, JavaScript executing within a browser can [by design] access only 6 of the HTTP headers actually sent by the HTTP server. If we would like the server to suggest a filename for the download, we must inform the browser that it is "OK" for JavaScript to be granted access to other headers where suggested filename would be transported.

Let us assume - for the sake of discussion - that we want the server to transmit the suggested filename within a HTTP header called X-Suggested-Filename. The HTTP server tells the browser that it is OK to expose this received custom header to the JavaScript/Axios with the following header:

Access-Control-Expose-Headers: X-Suggested-Filename

The exact way to configure your HTTP server to set this header varies from product to product.

See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers for full explanation and detailed description of these standard headers.

2. Implement the server-side service

Your server-side service implementation must now perform 2 things:

1. Create the (binary) document and assign correct ContentType to the response
2. Assign the custom header (X-Suggested-Filename) containing the suggested file name for the client

This is done in different ways depending on your chosen technology stack. I will sketch an example using the JavaEE 7 standard which should emit an Excel report:

@GET
@Path("/report/excel")
@Produces("application/vnd.ms-excel")
public Response getAllergyAndPreferencesReport() {

    // Create the document which should be downloaded
    final byte[] theDocumentData = .... 

    // Define a suggested filename
    final String filename = ... 

    // Create the JAXRS response
    // Don't forget to include the filename in 2 HTTP headers: 
    //
    // a) The standard 'Content-Disposition' one, and
    // b) The custom 'X-Suggested-Filename'  
    //
    final Response.ResponseBuilder builder = Response.ok(
            theDocumentData, "application/vnd.ms-excel")
            .header("X-Suggested-Filename", fileName);
    builder.header("Content-Disposition", "attachment; filename=" + fileName);

    // All Done.
    return builder.build();
}

The service now emits the binary document (an Excel report, in this case), sets the correct content type - and also sends a custom HTTP header containing the suggested filename to use when saving the document.

3. Implement an Axios handler for the Received document

There are a few pitfalls here, so let's ensure all details are correctly configured:

  1. The service responds to @GET (i.e. HTTP GET), so the axios call must be 'axios.get(...)'.
  2. The document is transmitted as a stream of bytes, so you must tell axios to treat the response as an HTML5 Blob. (I.e. responseType: 'blob').
  3. In this case, the file-saver JavaScript library is used to pop the browser dialog open. However, you could chose another.

The skeleton Axios implementation would then be something along the lines of:

 // Fetch the dynamically generated excel document from the server.
 axios.get(resource, {responseType: 'blob'}).then((response) => {

    // Log somewhat to show that the browser actually exposes the custom HTTP header
    const fileNameHeader = "x-suggested-filename";
    const suggestedFileName = response.headers[fileNameHeader];'
    const effectiveFileName = (suggestedFileName === undefined
                ? "allergierOchPreferenser.xls"
                : suggestedFileName);
    console.log("Received header [" + fileNameHeader + "]: " + suggestedFileName
                + ", effective fileName: " + effectiveFileName);

    // Let the user save the file.
    FileSaver.saveAs(response.data, effectiveFileName);

    }).catch((response) => {
        console.error("Could not Download the Excel report from the backend.", response);
    });

How to convert hex to ASCII characters in the Linux shell?

GNU awk 4.1

awk -niord '$0=chr("0x"RT)' RS=.. ORS=

Note that if you echo to this it will produce an extra null byte

$ echo 595a | awk -niord '$0=chr("0x"RT)' RS=.. ORS= | od -tx1c
0000000  59  5a  00
          Y   Z  \0

Instead use printf

$ printf 595a | awk -niord '$0=chr("0x"RT)' RS=.. ORS= | od -tx1c
0000000  59  5a
          Y   Z

Also note that GNU awk produces UTF-8 by default

$ printf a1 | awk -niord '$0=chr("0x"RT)' RS=.. ORS= | od -tx1
0000000 c2 a1

If you are dealing with characters outside of ASCII, and you are going to be Base64 encoding the resultant string, you can disable UTF-8 with -b

echo 5a | sha256sum | awk -bniord 'RT~/\w/,$0=chr("0x"RT)' RS=.. ORS=

Looping through rows in a DataView

I prefer to do it in a more direct fashion. It does not have the Rows but is still has the array of rows.

tblCrm.DefaultView.RowFilter = "customertype = 'new'";

qtytotal = 0;
for (int i = 0; i < tblCrm.DefaultView.Count; i++)
{
    result = double.TryParse(tblCrm.DefaultView[i]["qty"].ToString(), out num);
    if (result == false) num = 0;
    qtytotal = qtytotal + num;
}

labQty.Text = qtytotal.ToString();

How to get the top 10 values in postgresql?

Seems you are looking for ORDER BY in DESCending order with LIMIT clause:

SELECT
 *
FROM
  scores
ORDER BY score DESC
LIMIT 10

Of course SELECT * could seriously affect performance, so use it with caution.

Can we execute a java program without a main() method?

Now - no


Prior to Java 7:

Yes, sequence is as follows:

  • jvm loads class
  • executes static blocks
  • looks for main method and invokes it

So, if there's code in a static block, it will be executed. But there's no point in doing that.

How to test that:

public final class Test {
    static {
        System.out.println("FOO");
    }
}

Then if you try to run the class (either form command line with java Test or with an IDE), the result is:

FOO
java.lang.NoSuchMethodError: main

What's the difference between <mvc:annotation-driven /> and <context:annotation-config /> in servlet?

mvc:annotation-driven is a tag added in Spring 3.0 which does the following:

  1. Configures the Spring 3 Type ConversionService (alternative to PropertyEditors)
  2. Adds support for formatting Number fields with @NumberFormat
  3. Adds support for formatting Date, Calendar, and Joda Time fields with @DateTimeFormat, if Joda Time is on the classpath
  4. Adds support for validating @Controller inputs with @Valid, if a JSR-303 Provider is on the classpath
  5. Adds support for support for reading and writing XML, if JAXB is on the classpath (HTTP message conversion with @RequestBody/@ResponseBody)
  6. Adds support for reading and writing JSON, if Jackson is o n the classpath (along the same lines as #5)

context:annotation-config Looks for annotations on beans in the same application context it is defined and declares support for all the general annotations like @Autowired, @Resource, @Required, @PostConstruct etc etc.

find filenames NOT ending in specific extensions on Unix?

Or without ( and the need to escape it:

find . -not -name "*.exe" -not -name "*.dll"

and to also exclude the listing of directories

find . -not -name "*.exe" -not -name "*.dll" -not -type d

or in positive logic ;-)

find . -not -name "*.exe" -not -name "*.dll" -type f

How to get the body's content of an iframe in Javascript?

The exact question is how to do it with pure JavaScript not with jQuery.

But I always use the solution that can be found in jQuery's source code. It's just one line of native JavaScript.

For me it's the best, easy readable and even afaik the shortest way to get the iframes content.

First get your iframe

var iframe = document.getElementById('id_description_iframe');

// or
var iframe = document.querySelector('#id_description_iframe');

And then use jQuery's solution

var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

It works even in the Internet Explorer which does this trick during the contentWindow property of the iframe object. Most other browsers uses the contentDocument property and that is the reason why we proof this property first in this OR condition. If it is not set try contentWindow.document.

Select elements in iframe

Then you can usually use getElementById() or even querySelectorAll() to select the DOM-Element from the iframeDocument:

if (!iframeDocument) {
    throw "iframe couldn't be found in DOM.";
}

var iframeContent = iframeDocument.getElementById('frameBody');

// or
var iframeContent = iframeDocument.querySelectorAll('#frameBody');

Call functions in the iframe

Get just the window element from iframe to call some global functions, variables or whole libraries (e.g. jQuery):

var iframeWindow = iframe.contentWindow;

// you can even call jQuery or other frameworks
// if it is loaded inside the iframe
iframeContent = iframeWindow.jQuery('#frameBody');

// or
iframeContent = iframeWindow.$('#frameBody');

// or even use any other global variable
iframeWindow.myVar = window.myVar;

// or call a global function
var myVar = iframeWindow.myFunction(param1 /*, ... */);

Note

All this is possible if you observe the same-origin policy.

How to redirect on another page and pass parameter in url from table?

Bind the button, this is done with jQuery:

$("#my-table input[type='button']").click(function(){
    var parameter = $(this).val();
    window.location = "http://yoursite.com/page?variable=" + parameter;
});

How to find a value in an excel column by vba code Cells.Find

Just use

Dim Cell As Range
Columns("B:B").Select
Set cell = Selection.Find(What:="celda", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

If cell Is Nothing Then
    'do it something

Else
    'do it another thing
End If

Get Value of Radio button group

Your quotes only need to surround the value part of the attribute-equals selector, [attr='val'], like this:

$('a#check_var').click(function() {
  alert($("input:radio[name='r']:checked").val()+ ' '+
        $("input:radio[name='s']:checked").val());
});?

You can see the working version here.

show/hide html table columns using css

I don't think there is anything you can do to avoid what you are already doing, however, if you are building the table on the client with javascript, you can always add the style rules dynamically, so you can allow for any number of columns without cluttering up your css file with all those rules. See http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript if you don't know how to do this.

Edit: For your "sticky" toggle, you should just append class names rather than replacing them. For instance, you can give it a class name of "hide2 hide3" etc. I don't think you really need the "show" classes, since that would be the default. Libraries like jQuery make this easy, but in the absence, a function like this might help:

var modifyClassName = function (elem, add, string) {
var s = (elem.className) ? elem.className : "";
var a = s.split(" ");
if (add) {
  for (var i=0; i<a.length; i++) {
      if (a[i] == string) {
          return;
          }
      }
  s += " " + string;
  }
else {
    s = "";
    for (var i=0; i<a.length; i++) {
        if (a[i] != string)
            s += a[i] + " "; 
        }
    }
elem.className = s;
}

Passing two command parameters using a WPF binding

This task can also be solved with a different approach. Instead of programming a converter and enlarging the code in the XAML, you can also aggregate the various parameters in the ViewModel. As a result, the ViewModel then has one more property that contains all parameters.

An example of my current application, which also let me deal with the topic. A generic RelayCommand is required: https://stackoverflow.com/a/22286816/7678085

The ViewModelBase is extended here by a command SaveAndClose. The generic type is a named tuple that represents the various parameters.

public ICommand SaveAndCloseCommand => saveAndCloseCommand ??= new RelayCommand<(IBaseModel Item, Window Window)>
    (execute =>
    {
        execute.Item.Save();
        execute.Window?.Close(); // if NULL it isn't closed.
    },
    canExecute =>
    {
        return canExecute.Item?.IsItemValide ?? false;
    });
private ICommand saveAndCloseCommand;

Then it contains a property according to the generic type:

public (IBaseModel Item, Window Window) SaveAndCloseParameter 
{ 
    get => saveAndCloseParameter ; 
    set 
    {
        SetProperty(ref saveAndCloseParameter, value);
    }
}
private (IBaseModel Item, Window Window) saveAndCloseParameter;

The XAML code of the view then looks like this: (Pay attention to the classic click event)

<Button 
    Command="{Binding SaveAndCloseCommand}" 
    CommandParameter="{Binding SaveAndCloseParameter}" 
    Click="ButtonApply_Click" 
    Content="Apply"
    Height="25" Width="100" />
<Button 
    Command="{Binding SaveAndCloseCommand}" 
    CommandParameter="{Binding SaveAndCloseParameter}" 
    Click="ButtonSave_Click" 
    Content="Save"
    Height="25" Width="100" />

and in the code behind of the view, then evaluating the click events, which then set the parameter property.

private void ButtonApply_Click(object sender, RoutedEventArgs e)
{
    computerViewModel.SaveAndCloseParameter = (computerViewModel.Computer, null);
}

private void ButtonSave_Click(object sender, RoutedEventArgs e)
{
    computerViewModel.SaveAndCloseParameter = (computerViewModel.Computer, this);
}

Personally, I think that using the click events is not a break with the MVVM pattern. The program flow control is still located in the area of ??the ViewModel.

How to remove decimal values from a value of type 'double' in Java

Nice and simple. Add this snippet in whatever you're outputting to:

String.format("%.0f", percentageValue)

changing kafka retention period during runtime

log.retention.hours is a property of a broker which is used as a default value when a topic is created. When you change configurations of currently running topic using kafka-topics.sh, you should specify a topic-level property.

A topic-level property for log retention time is retention.ms.

From Topic-level configuration in Kafka 0.8.1 documentation:

  • Property: retention.ms
  • Default: 7 days
  • Server Default Property: log.retention.minutes
  • Description: This configuration controls the maximum time we will retain a log before we will discard old log segments to free up space if we are using the "delete" retention policy. This represents an SLA on how soon consumers must read their data.

So the correct command depends on the version. Up to 0.8.2 (although docs still show its use up to 0.10.1) use kafka-topics.sh --alter and after 0.10.2 (or perhaps from 0.9.0 going forward) use kafka-configs.sh --alter

$ bin/kafka-topics.sh --zookeeper zk.yoursite.com --alter --topic as-access --config retention.ms=86400000
 

You can check whether the configuration is properly applied with the following command.

$ bin/kafka-topics.sh --describe --zookeeper zk.yoursite.com --topic as-access

Then you will see something like below.

Topic:as-access  PartitionCount:3  ReplicationFactor:3  Configs:retention.ms=86400000

How to embed a .mov file in HTML?

Had issues using the code in the answer provided by @haynar above (wouldn't play on Chrome), and it seems that one of the more modern ways to ensure it plays is to use the video tag

Example:

<video controls="controls" width="800" height="600" 
       name="Video Name" src="http://www.myserver.com/myvideo.mov"></video>

This worked like a champ for my .mov file (generated from Keynote) in both Safari and Chrome, and is listed as supported in most modern browsers (The video tag is supported in Internet Explorer 9+, Firefox, Opera, Chrome, and Safari.)

Note: Will work in IE / etc.. if you use MP4 (Mov is not officially supported by those guys)

How to set conditional breakpoints in Visual Studio?

Writing the actual condition can be the tricky part, so I tend to

  1. Set a regular breakpoint.
  2. Run the code until the breakpoint is hit for the first time.
  3. Use the Immediate Window (Debug > Windows > Immediate) to test your expression.
  4. Right-click the breakpoint, click Condition and paste in your expression.

Advantages of using the Immediate window:

  • It has IntelliSense.
  • You can be sure that the variables in the expression are in scope when the expression is evaluated.
  • You can be sure your expression returns true or false.

This example breaks when the code is referring to a table with the name "Setting":

table.GetTableName().Contains("Setting")

Creating a "logical exclusive or" operator in Java

That's because operator overloading is something they specifically left out of the language deliberately. They "cheated" a bit with string concatenation, but beyond that, such functionality doesn't exist.

(disclaimer: I haven't worked with the last 2 major releases of java, so if it's in now, I'll be very surprised)

Detecting installed programs via registry

You can use a PowerShell script to look at registers and get the installed program details. The script bellow will generate a file with the complete list of installed programs. Save it with ".ps" extension and double click the file.

#
# Generates a full list of installed programs.
#

# Temporary auxiliar file.
$tmpFile = "tmp.txt"

# File that will hold the programs list.
$fileName = "programas-instalados.txt"

# Columns separator.
$separator = ","

# Delete previous files.
Remove-Item $tmpFile
Remove-Item $fileName

# Creates the temporary file.
Create-Item $tmpFile

# Searchs register for programs - part 1
$loc = Get-ChildItem HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall
$names = $loc |foreach-object {Get-ItemProperty $_.PsPath}
foreach ($name in $names)
{
    IF(-Not [string]::IsNullOrEmpty($name.DisplayName)) {      
        $line = $name.DisplayName+$separator+$name.DisplayVersion+$separator+$name.InstallDate
        Write-Host $line
        Add-Content $tmpFile "$line`n"        
    }
}

# Searchs register for programs - part 2
$loc = Get-ChildItem HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall
$names = $loc |foreach-object {Get-ItemProperty $_.PsPath}
foreach ($name in $names)
{
    IF(-Not [string]::IsNullOrEmpty($name.DisplayName)) {      
        $line = $name.DisplayName+$separator+$name.DisplayVersion+$separator+$name.InstallDate
        Write-Host $line
        Add-Content $tmpFile "$line`n"
    }
}

# Sorts the result, removes duplicate lines and
# generates the final file.
gc $tmpFile | sort | get-unique > $filename

How can I prevent the backspace key from navigating back?

Based on the comments it appears you want to stop people losing information in forms, if they press backspace to delete but the field is not focused.

In which case, you want to look at the onunload event handler. Stack Overflow uses it - if you try to leave a page when you've started writing an answer, it pops up a warning.

Java collections convert a string to a list of characters

Using Java 8 - Stream Funtion:

Converting A String into Character List:

ArrayList<Character> characterList =  givenStringVariable
                                                         .chars()
                                                         .mapToObj(c-> (char)c)
                                                         .collect(collectors.toList());

Converting A Character List into String:

 String givenStringVariable =  characterList
                                            .stream()
                                            .map(String::valueOf)
                                            .collect(Collectors.joining())

How to check whether a file is empty or not?

If you are using Python3 with pathlib you can access os.stat() information using the Path.stat() method, which has the attribute st_size(file size in bytes):

>>> from pathlib import Path 
>>> mypath = Path("path/to/my/file")
>>> mypath.stat().st_size == 0 # True if empty

Detect page change on DataTable

If you handle the draw.dt event after page.dt, you can detect exactly after moving the page. After work, draw.dt must be unbind

    $(document).on("page.dt", () => {
        $(document).on("draw.dt", changePage);
    });

    const changePage = () => {
        // TODO
        $(document).unbind("draw.dt", changePage);
    } 

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

It is indeed a foreign key error, you can find out using perror:

shell$ perror 150
MySQL error code 150: Foreign key constraint is incorrectly formed

To find out more details about what failed, you can use SHOW ENGINE INNODB STATUS and look for the LATEST FOREIGN KEY ERROR section it contains details about what is wrong.

In your case, it is most likely cause something is referencing the country_id column.

How to call javascript function on page load in asp.net

Calling JavaScript function on code behind i.e. On Page_Load

ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);

If you have UpdatePanel there then try like this

ScriptManager.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);

View Blog Article : How to Call javascript function from code behind in asp.net c#

Where to change the value of lower_case_table_names=2 on windows xampp

I have same problem while importing database from linux to Windows. It lowercases Database name aswell as Tables' name. Use following steps for same problem:

  1. Open c:\xampp\mysql\bin\my.ini in editor.
  2. look for

# The MySQL server

[mysqld]

3 . Find

lower_case_table_names

and change value to 2


if not avail copy this at the end of this [mysqld] portion.

lower_case_table_names = 2

This will surely work.

How to clone all remote branches in Git?

Use commands that you can remember

I'm using Bitbucket, a Repository Hosting Service of Atlassian. So I try to follow their docs. And that works perfectly for me. With the following easy and short commands you can checkout your remote branch.

At first clone your repository, then change into the destination folder. And last but not least fetch and checkout:

git clone <repo> <destination_folder>
cd <destination_folder>
git fetch && git checkout <branch>

That's it. Here a litte more real world example:

git clone https://[email protected]/team/repository.git project_folder
cd project_folder
git fetch && git checkout develop

You will find detail information about the commands in the docs: Clone Command, Fetch Command, Checkout Command

Capturing image from webcam in java?

http://grack.com/downloads/school/enel619.10/report/java_media_framework.html

Using the Player with Swing

The Player can be easily used in a Swing application as well. The following code creates a Swing-based TV capture program with the video output displayed in the entire window:

import javax.media.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import javax.swing.event.*;

public class JMFTest extends JFrame {
    Player _player;
    JMFTest() {
        addWindowListener( new WindowAdapter() {
            public void windowClosing( WindowEvent e ) {
                _player.stop();
                _player.deallocate();
                _player.close();
                System.exit( 0 );
            }
        });
          setExtent( 0, 0, 320, 260 );
        JPanel panel = (JPanel)getContentPane();
        panel.setLayout( new BorderLayout() );
        String mediaFile = "vfw://1";
        try {
            MediaLocator mlr = new MediaLocator( mediaFile );
            _player = Manager.createRealizedPlayer( mlr );
            if (_player.getVisualComponent() != null)
            panel.add("Center", _player.getVisualComponent());
            if (_player.getControlPanelComponent() != null)
            panel.add("South", _player.getControlPanelComponent());
        }
        catch (Exception e) {
            System.err.println( "Got exception " + e );
        }
    }

    public static void main(String[] args) {
        JMFTest jmfTest = new JMFTest();
        jmfTest.show();
    }
}

Execute Stored Procedure from a Function

EDIT: I haven't tried this, so I can't vouch for it! And you already know you shouldn't be doing this, so please don't do it. BUT...

Try looking here: http://sqlblog.com/blogs/denis_gobo/archive/2008/05/08/6703.aspx

The key bit is this bit which I have attempted to tweak for your purposes:

DECLARE @SQL varchar(500)

SELECT @SQL = 'osql -S' +@@servername +' -E -q "exec dbName..sprocName "'

EXEC master..xp_cmdshell @SQL

Explicit Return Type of Lambda

The return type of a lambda (in C++11) can be deduced, but only when there is exactly one statement, and that statement is a return statement that returns an expression (an initializer list is not an expression, for example). If you have a multi-statement lambda, then the return type is assumed to be void.

Therefore, you should do this:

  remove_if(rawLines.begin(), rawLines.end(), [&expression, &start, &end, &what, &flags](const string& line) -> bool
  {
    start = line.begin();
    end = line.end();
    bool temp = boost::regex_search(start, end, what, expression, flags);
    return temp;
  })

But really, your second expression is a lot more readable.

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

How to connect to Mysql Server inside VirtualBox Vagrant?

Make sure MySQL binds to 0.0.0.0 and not 127.0.0.1 or it will not be accessible from outside the machine

You can ensure this by editing your my.conf file and looking for the bind-address item--you want it to look like bind-address = 0.0.0.0. Then save this and restart mysql:

sudo service mysql restart

If you are doing this on a production server, you want to be aware of the security implications, discussed here: https://serverfault.com/questions/257513/how-bad-is-setting-mysqls-bind-address-to-0-0-0-0

How to vertically align text with icon font?

In this scenario, since you are working with inline-level elements, you could add vertical-align: middle to the span elements for vertical centering:

.nav-text {
  vertical-align: middle;
}

Alternatively, you could set the display of the parent element to flex and set align-items to center for vertical centering:

.menu {
  display: flex;
  align-items: center;
}

How to check if a symlink exists

If you are testing for file existence you want -e not -L. -L tests for a symlink.

Checking for empty queryset in Django

If you have a huge number of objects, this can (at times) be much faster:

try:
    orgs[0]
    # If you get here, it exists...
except IndexError:
    # Doesn't exist!

On a project I'm working on with a huge database, not orgs is 400+ ms and orgs.count() is 250ms. In my most common use cases (those where there are results), this technique often gets that down to under 20ms. (One case I found, it was 6.)

Could be much longer, of course, depending on how far the database has to look to find a result. Or even faster, if it finds one quickly; YMMV.

EDIT: This will often be slower than orgs.count() if the result isn't found, particularly if the condition you're filtering on is a rare one; as a result, it's particularly useful in view functions where you need to make sure the view exists or throw Http404. (Where, one would hope, people are asking for URLs that exist more often than not.)

How to increment a JavaScript variable using a button press event

The purist way to do this would be to add event handlers to the button, instead of mixing behavior with the content (LSM, Layered Semantic Markup)

<input type="button" value="Increment" id="increment"/>

<script type="text/javascript">
    var count = 0;
    // JQuery way
    $('#increment').click(function (e) {
        e.preventDefault();
        count++;
    });
    // YUI way
    YAHOO.util.Event.on('increment', 'click', function (e) {
        YAHOO.util.Event.preventDefault(e);
        count++;
    });
    // Simple way
    document.getElementById('increment').onclick = function (e) {
        count++;
        if (e.preventDefault) {
            e.preventDefault();
        }
        e.returnValue = false;
    };
</script>

XML Error: Extra content at the end of the document

I've found that this error is also generated if the document is empty. In this case it's also because there is no root element - but the error message "Extra content and the end of the document" is misleading in this situation.

How to use std::sort to sort an array in C++

C++ sorting using sort function

#include <bits/stdc++.h>
 using namespace std;

vector <int> v[100];

int main()
{
  sort(v.begin(), v.end());
}

select dept names who have more than 2 employees whose salary is greater than 1000

select deptname from dept_1
where exists
(
SELECT DeptId,COUNT(*)        
FROM emp_1  
where salary>1000
and emp_1.deptid=dept_1.deptid   
GROUP BY DeptId 
having count(*)>2)

Transpose/Unzip Function (inverse of zip)?

>>> original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> tuple([list(tup) for tup in zip(*original)])
(['a', 'b', 'c', 'd'], [1, 2, 3, 4])

Gives a tuple of lists as in the question.

list1, list2 = [list(tup) for tup in zip(*original)]

Unpacks the two lists.

Printing the correct number of decimal points with cout

With <iomanip>, you can use std::fixed and std::setprecision

Here is an example

#include <iostream>
#include <iomanip>

int main()
{
    double d = 122.345;

    std::cout << std::fixed;
    std::cout << std::setprecision(2);
    std::cout << d;
}

And you will get output

122.34

Setting log level of message at runtime in slf4j

using java introspection you can do it, for example:

private void changeRootLoggerLevel(int level) {

    if (logger instanceof org.slf4j.impl.Log4jLoggerAdapter) {
        try {
            Class loggerIntrospected = logger.getClass();
            Field fields[] = loggerIntrospected.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                String fieldName = fields[i].getName();
                if (fieldName.equals("logger")) {
                    fields[i].setAccessible(true);
                    org.apache.log4j.Logger loggerImpl = (org.apache.log4j.Logger) fields[i]
                            .get(logger);

                    if (level == DIAGNOSTIC_LEVEL) {
                        loggerImpl.setLevel(Level.DEBUG);
                    } else {
                        loggerImpl.setLevel(org.apache.log4j.Logger.getRootLogger().getLevel());
                    }

                    // fields[i].setAccessible(false);
                }
            }
        } catch (Exception e) {
            org.apache.log4j.Logger.getLogger(LoggerSLF4JImpl.class).error("An error was thrown while changing the Logger level", e);
        }
    }

}

Copying and pasting data using VBA code

'So from this discussion i am thinking this should be the code then.

Sub Button1_Click()
    Dim excel As excel.Application
    Dim wb As excel.Workbook
    Dim sht As excel.Worksheet
    Dim f As Object

    Set f = Application.FileDialog(3)
    f.AllowMultiSelect = False
    f.Show

    Set excel = CreateObject("excel.Application")
    Set wb = excel.Workbooks.Open(f.SelectedItems(1))
    Set sht = wb.Worksheets("Data")

    sht.Activate
    sht.Columns("A:G").Copy
    Range("A1").PasteSpecial Paste:=xlPasteValues


    wb.Close
End Sub

'Let me know if this is correct or a step was missed. Thx.

ImportError: No module named PIL

I used conda-forge to install pillow version 5, and that seemed to work for me:

conda install --channel conda-forge pillow=5

the normal conda install pillow did NOT work for me.

RE error: illegal byte sequence on Mac OS X

Does anyone know how to get sed to print the position of the illegal byte sequence? Or does anyone know what the illegal byte sequence is?

$ uname -a
Darwin Adams-iMac 18.7.0 Darwin Kernel Version 18.7.0: Tue Aug 20 16:57:14 PDT 2019; root:xnu-4903.271.2~2/RELEASE_X86_64 x86_64

I got part of the way to answering the above just by using tr.

I have a .csv file that is a credit card statement and I am trying to import it into Gnucash. I am based in Switzerland so I have to deal with words like Zürich. Suspecting Gnucash does not like " " in numeric fields, I decide to simply replace all

; ;

with

;;

Here goes:

$ head -3 Auswertungen.csv | tail -1 | sed -e 's/; ;/;;/g'
sed: RE error: illegal byte sequence

I used od to shed some light: Note the 374 halfway down this od -c output

$ head -3 Auswertungen.csv | tail -1 | od -c
0000000    1   6   8   7       9   6   1   9       7   1   2   2   ;   5
0000020    4   6   8       8   7   X   X       X   X   X   X       2   6
0000040    6   0   ;   M   Y       N   A   M   E       I   S   X   ;   1
0000060    4   .   0   2   .   2   0   1   9   ;   9   5   5   2       -
0000100        M   i   t   a   r   b   e   i   t   e   r   r   e   s   t
0000120                Z 374   r   i   c   h                            
0000140    C   H   E   ;   R   e   s   t   a   u   r   a   n   t   s   ,
0000160        B   a   r   s   ;   6   .   2   0   ;   C   H   F   ;    
0000200    ;   C   H   F   ;   6   .   2   0   ;       ;   1   5   .   0
0000220    2   .   2   0   1   9  \n                                    
0000227

Then I thought I might try to persuade tr to substitute 374 for whatever the correct byte code is. So first I tried something simple, which didn't work, but had the side effect of showing me where the troublesome byte was:

$ head -3 Auswertungen.csv | tail -1 | tr . .  ; echo
tr: Illegal byte sequence
1687 9619 7122;5468 87XX XXXX 2660;MY NAME ISX;14.02.2019;9552 - Mitarbeiterrest   Z

You can see tr bails at the 374 character.

Using perl seems to avoid this problem

$ head -3 Auswertungen.csv | tail -1 | perl -pne 's/; ;/;;/g'
1687 9619 7122;5468 87XX XXXX 2660;ADAM NEALIS;14.02.2019;9552 - Mitarbeiterrest   Z?rich       CHE;Restaurants, Bars;6.20;CHF;;CHF;6.20;;15.02.2019

Python error when trying to access list by index - "List indices must be integers, not str"

A list is a chain of spaces that can be indexed by (0, 1, 2 .... etc). So if players was a list, players[0] or players[1] would have worked. If players is a dictionary, players["name"] would have worked.

Error: "Could Not Find Installable ISAM"

Use this connection string

string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
      "Data Source=" + strFileName + ";" + "Extended Properties=" + "\"" + "Excel 12.0;HDR=YES;" + "\"";

Insert PHP code In WordPress Page and Post

When I was trying to accomplish something very similar, I ended up doing something along these lines:

wp-content/themes/resources/functions.php

add_action('init', 'my_php_function');
function my_php_function() {
    if (stripos($_SERVER['REQUEST_URI'], 'page-with-custom-php') !== false) {
        // add desired php code here
    }
}

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

Go to the folder in which you have Node and NPM (such as C:\Program Files (x86)\nodejs\) and type the following:

> set path=%PATH%;%CD%
> setx path "%PATH%"

From http://www.hacksparrow.com/install-node-js-and-npm-on-windows.html

How to change language of app when user selects language?

It's excerpt for the webpage: http://android.programmerguru.com/android-localization-at-runtime/

It's simple to change the language of your app upon user selects it from list of languages. Have a method like below which accepts the locale as String (like 'en' for English, 'hi' for hindi), configure the locale for your App and refresh your current activity to reflect the change in language. The locale you applied will not be changed until you manually change it again.

public void setLocale(String lang) { 
    Locale myLocale = new Locale(lang); 
    Resources res = getResources(); 
    DisplayMetrics dm = res.getDisplayMetrics(); 
    Configuration conf = res.getConfiguration(); 
    conf.locale = myLocale; 
    res.updateConfiguration(conf, dm); 
    Intent refresh = new Intent(this, AndroidLocalize.class); 
    finish();
    startActivity(refresh); 
} 

Make sure you imported following packages:

import java.util.Locale; 
import android.os.Bundle; 
import android.app.Activity; 
import android.content.Intent; 
import android.content.res.Configuration; 
import android.content.res.Resources; 
import android.util.DisplayMetrics; 

add in manifest to activity android:configChanges="locale|orientation"

Can't ignore UserInterfaceState.xcuserstate

This works for me

  1. Open the folder which contains the project file project.xcworkspace from the terminal.

  2. Write this command: git rm --cached *xcuserstate

This will remove the file.

Checking Bash exit status of several commands efficiently

Sorry that I can not make a comment to the first answer But you should use new instance to execute the command: cmd_output=$($@)

#!/bin/bash

function check_exit {
    cmd_output=$($@)
    local status=$?
    echo $status
    if [ $status -ne 0 ]; then
        echo "error with $1" >&2
    fi
    return $status
}

function run_command() {
    exit 1
}

check_exit run_command

Android Recyclerview GridLayoutManager column spacing

yqritc's answer worked perfectly for me. I was using Kotlin however so here is the equivalent of that.

class ItemOffsetDecoration : RecyclerView.ItemDecoration  {

    // amount to add to padding
    private val _itemOffset: Int

    constructor(itemOffset: Int) {
        _itemOffset = itemOffset
    }

    constructor(@NonNull context: Context, @DimenRes itemOffsetId: Int){
       _itemOffset = context.resources.getDimensionPixelSize(itemOffsetId)
    }

    /**
     * Applies padding to all sides of the [Rect], which is the container for the view
     */
    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView,state: RecyclerView.State) {
        super.getItemOffsets(outRect, view, parent, state)
        outRect.set(_itemOffset, _itemOffset, _itemOffset, _itemOffset)
    }
}

everything else is the same.

How can I exclude a directory from Visual Studio Code "Explore" tab?

In version 1.28 of Visual Studio Code "files.exclude" must be placed within a settings node.

Resulting in a workspace file that looks like:

{
    "settings": {
        "files.exclude": {
            "**/node_modules": true
        }
    }
}

SQL Server stored procedure parameters

Why would you pass a parameter to a stored procedure that doesn't use it?

It sounds to me like you might be better of building dynamic SQL statements and then executing them. What you are trying to do with the SP won't work, and even if you could change what you are doing in such a way to accommodate varying numbers of parameters, you would then essentially be using dynamically generated SQL you are defeating the purpose of having/using a SP in the first place. SP's have a role, but there are not the solution in all cases.

Change Text Color of Selected Option in a Select Box

You could do it like this.

jsFiddle

JS

var select = document.getElementById('mySelect');
select.onchange = function () {
    select.className = this.options[this.selectedIndex].className;
}

CSS

.redText {
    background-color:#F00;
}
.greenText {
    background-color:#0F0;
}
.blueText {
    background-color:#00F;
}

You could use option { background-color: #FFF; } if you want the list to be white.

HTML

<select id="mySelect" class="greenText">
    <option class="greenText" value="apple" >Apple</option>
    <option class="redText"   value="banana" >Banana</option>
    <option class="blueText" value="grape" >Grape</option>
</select>

Since this is a select it doesn't really make sense to use .yellowText as none selected if that's what you were getting at as something must be selected.

How to List All Redis Databases?

There is no command to do it (like you would do it with MySQL for instance). The number of Redis databases is fixed, and set in the configuration file. By default, you have 16 databases. Each database is identified by a number (not a name).

You can use the following command to know the number of databases:

CONFIG GET databases
1) "databases"
2) "16"

You can use the following command to list the databases for which some keys are defined:

INFO keyspace
# Keyspace
db0:keys=10,expires=0
db1:keys=1,expires=0
db3:keys=1,expires=0

Please note that you are supposed to use the "redis-cli" client to run these commands, not telnet. If you want to use telnet, then you need to run these commands formatted using the Redis protocol.

For instance:

*2
$4
INFO
$8
keyspace

$79
# Keyspace
db0:keys=10,expires=0
db1:keys=1,expires=0
db3:keys=1,expires=0

You can find the description of the Redis protocol here: http://redis.io/topics/protocol

What is the standard exception to throw in Java for not supported/implemented operations?

If you create a new (not yet implemented) function in NetBeans, then it generates a method body with the following statement:

throw new java.lang.UnsupportedOperationException("Not supported yet.");

Therefore, I recommend to use the UnsupportedOperationException.

How to copy selected files from Android with adb pull

Pull multiple files using regex:

Create pullFiles.sh:

#!/bin/bash
HOST_DIR=<pull-to>
DEVICE_DIR=/sdcard/<pull-from>
EXTENSION=".jpg"

for file in $(adb shell ls $DEVICE_DIR | grep $EXTENSION'$')
do
    file=$(echo -e $file | tr -d "\r\n"); # EOL fix
    adb pull $DEVICE_DIR/$file $HOST_DIR/$file;
done

Run it:

Make it executable: chmod +x pullFiles.sh

Run it: ./pullFiles.sh

Notes:

  • as is, won't work when filenames have spaces
  • includes a fix for end-of-line (EOL) on Android, which is a "\r\n"

How to install pip in CentOS 7?

Figure out what version of python3 you have installed:

yum search pip

and then install the best match. Use reqoquery to find name of resulting pip3.e.g

repoquery -l python36u-pip

tells me to use pip3.6 instead of pip3

Appending a list or series to a pandas DataFrame as a row?

Converting the list to a data frame within the append function works, also when applied in a loop

import pandas as pd
mylist = [1,2,3]
df = pd.DataFrame()
df = df.append(pd.DataFrame(data[mylist]))

How to disable submit button once it has been clicked?

function xxxx() {
// submit or validate here , disable after that using below
  document.getElementById('buttonId').disabled = 'disabled';
  document.getElementById('buttonId').disabled = '';
}

Auto logout with Angularjs based on idle user

I have used ng-idle for this and added a little logout and token null code and it is working fine, you can try this. Thanks @HackedByChinese for making such a nice module.

In IdleTimeout i have just deleted my session data and token.

Here is my code

$scope.$on('IdleTimeout', function () {
        closeModals();
        delete $window.sessionStorage.token;
        $state.go("login");
        $scope.timedout = $uibModal.open({
            templateUrl: 'timedout-dialog.html',
            windowClass: 'modal-danger'
        });
    });

How to terminate a process in vbscript

The Win32_Process class provides access to both 32-bit and 64-bit processes when the script is run from a 64-bit command shell.

If this is not an option for you, you can try using the taskkill command:

Dim oShell : Set oShell = CreateObject("WScript.Shell")

' Launch notepad '
oShell.Run "notepad"
WScript.Sleep 3000

' Kill notepad '
oShell.Run "taskkill /im notepad.exe", , True

How to drop columns by name in a data frame

I can´t answer your question in the comments due to low reputation score.

The next code will give you an error because the paste function return a character string

for(i in 1:length(var.out)) {
   paste("data$", var.out[i], sep="") <- NULL
}

Here is a possible solution:

for(i in 1:length(var.out)) {

  text_to_source <- paste0 ("data$", var.out[i], "<- NULL") # Write a line of your
                                                  # code like a character string
  eval (parse (text=text_to_source)) # Source a text that contains a code
}

or just do:

for(i in 1:length(var.out)) {
  data[var.out[i]] <- NULL
}

Imported a csv-dataset to R but the values becomes factors

When importing csv data files the import command should reflect both the data seperation between each column (;) and the float-number seperator for your numeric values (for numerical variable = 2,5 this would be ",").

The command for importing a csv, therefore, has to be a bit more comprehensive with more commands:

    stuckey <- read.csv2("C:/kalle/R/stuckey.csv", header=TRUE, sep=";", dec=",")

This should import all variables as either integers or numeric.

Spring MVC Controller redirect using URL parameters instead of in response

This problem is caused (as others have stated) by model attributes being persisted into the query string - this is usually undesirable and is at risk of creating security holes as well as ridiculous query strings. My usual solution is to never use Strings for redirects in Spring MVC, instead use a RedirectView which can be configured not to expose model attributes (see: http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/servlet/view/RedirectView.html)

RedirectView(String url, boolean contextRelative, boolean http10Compatible, boolean exposeModelAttributes)

So I tend to have a util method which does a 'safe redirect' like:

public static RedirectView safeRedirect(String url) {
    RedirectView rv = new RedirectView(url);
    rv.setExposeModelAttributes(false);
    return rv;
}

The other option is to use bean configuration XML:

<bean id="myBean" class="org.springframework.web.servlet.view.RedirectView">
   <property name="exposeModelAttributes" value="false" />
   <property name="url" value="/myRedirect"/>
</bean>

Again, you could abstract this into its own class to avoid repetition (e.g. SafeRedirectView).


A note about 'clearing the model' - this is not the same as 'not exposing the model' in all circumstances. One site I worked on had a lot of filters which added things to the model, this meant that clearing the model before redirecting would not prevent a long query string. I would also suggest that 'not exposing model attributes' is a more semantic approach than 'clearing the model before redirecting'.

SQL Server : Transpose rows to columns

One way to do it if tagID values are known upfront is to use conditional aggregation

SELECT TimeSeconds,
       COALESCE(MAX(CASE WHEN TagID = 'A1' THEN Value END), 'n/a') A1,
       COALESCE(MAX(CASE WHEN TagID = 'A2' THEN Value END), 'n/a') A2,
       COALESCE(MAX(CASE WHEN TagID = 'A3' THEN Value END), 'n/a') A3,
       COALESCE(MAX(CASE WHEN TagID = 'A4' THEN Value END), 'n/a') A4
  FROM table1
 GROUP BY TimeSeconds

or if you're OK with NULL values instead of 'n/a'

SELECT TimeSeconds,
       MAX(CASE WHEN TagID = 'A1' THEN Value END) A1,
       MAX(CASE WHEN TagID = 'A2' THEN Value END) A2,
       MAX(CASE WHEN TagID = 'A3' THEN Value END) A3,
       MAX(CASE WHEN TagID = 'A4' THEN Value END) A4
  FROM table1
 GROUP BY TimeSeconds

or with PIVOT

SELECT TimeSeconds, A1, A2, A3, A4
  FROM
(
  SELECT TimeSeconds, TagID, Value
    FROM table1
) s
PIVOT
(
  MAX(Value) FOR TagID IN (A1, A2, A3, A4)
) p

Output (with NULLs):

TimeSeconds A1      A2     A3    A4
----------- ------- ------ ----- -----
1378700244  3.75    NULL   NULL  NULL
1378700245  30.00   NULL   NULL  NULL
1378700304  1.20    NULL   NULL  NULL
1378700305  NULL    56.00  NULL  NULL
1378700344  NULL    11.00  NULL  NULL
1378700345  NULL    NULL   0.53  NULL
1378700364  4.00    NULL   NULL  NULL
1378700365  14.50   NULL   NULL  NULL
1378700384  144.00  NULL   NULL  10.00

If you have to figure TagID values out dynamically then use dynamic SQL

DECLARE @cols NVARCHAR(MAX), @sql NVARCHAR(MAX)

SET @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(TagID)
            FROM Table1
            ORDER BY 1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)'),1,1,'')

SET @sql = 'SELECT TimeSeconds, ' + @cols + '
              FROM
            (
              SELECT TimeSeconds, TagID, Value
                FROM table1
            ) s
            PIVOT
            (
              MAX(Value) FOR TagID IN (' + @cols + ')
            ) p'

EXECUTE(@sql)

Unable to launch the IIS Express Web server

It seems you need to do some configuring as you seem to be using SSL; here's a step-by-step guide by Scott Hanselman himself.

What is "with (nolock)" in SQL Server?

Use nolock when you are okay with the "dirty" data. Which means nolock can also read data which is in the process of being modified and/or uncommitted data.

It's generally not a good idea to use it in high transaction environment and that is why it is not a default option on query.

How do I configure php to enable pdo and include mysqli on CentOS?

You might just have to install the packages.

yum install php-pdo php-mysqli

After they're installed, restart Apache.

httpd restart

or

apachectl restart

Listing available com ports with Python

try this code

import serial.tools.list_ports
for i in serial.tools.list_ports.comports():
    print(i) 

it returns

COM1 - Port de communication (COM1)
COM5 - USB-SERIAL CH340 (COM5)

if you just wont the name of the port for exemple COM1

import serial.tools.list_ports
for i in serial.tools.list_ports.comports():
    print(str(i).split(" ")[0])

it returns

COM1
COM5

as in my case py 3.7 64bits

changing default x range in histogram matplotlib

plt.hist(hmag, 30, range=[6.5, 12.5], facecolor='gray', align='mid')

AttributeError: 'module' object has no attribute 'urlopen'

Change TWO lines:

import urllib.request #line1

#Replace
urllib.urlopen("http://www.python.org")
#To
urllib.request.urlopen("http://www.python.org") #line2

If You got ERROR 403: Forbidden Error exception try this:

siteurl = "http://www.python.org"

req = urllib.request.Request(siteurl, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36'})
pageHTML = urllib.request.urlopen(req).read()

I hope your problem resolved.

Force Java timezone as GMT/UTC

I had to set the JVM timezone for Windows 2003 Server because it always returned GMT for new Date();

-Duser.timezone=America/Los_Angeles

Or your appropriate time zone. Finding a list of time zones proved to be a bit challenging also...

Here are two list;

http://wrapper.tanukisoftware.com/doc/english/prop-timezone.html

http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Frzatz%2F51%2Fadmin%2Freftz.htm

Package php5 have no installation candidate (Ubuntu 16.04)

Currently, I am using Ubuntu 16.04 LTS. Me too was facing same problem while Fetching the Postgress Database values using Php so i resolved it by using the below commands.

Mine PHP version is 7.0, so i tried the below command.

apt-get install php-pgsql

Remember to restart Apache.

/etc/init.d/apache2 restart

Error: free(): invalid next size (fast):

I encountered the same problem, even though I did not make any dynamic memory allocation in my program, but I was accessing a vector's index without allocating memory for it. So, if the same case, better allocate some memory using resize() and then access vector elements.

C# Copy a file to another location with a different name

File.Copy(@"C:\oldFile.txt", @"C:\newFile.txt", true);

Please do not forget to overwrite the previous file! Make sure you add the third param., by adding the third param, you allow the file to be overwritten. Else you could use a try catch for the exception.

Regards, G

Install mysql-python (Windows)

For folks using Python 3.0+ (which should be everyone now):

Unfortunately, MySQL-Python 1.2.5 does not support Python 3.0+ yet (which is kinda unreasonable IMHO, Python 3+ has been out for a while). Reference : https://pypi.python.org/pypi/MySQL-python/1.2.5

So, my workaround is to use Oracle's MySQL connector. In settings.py, change DATABASE's 'ENGINE' field to: 'ENGINE': 'mysql.connector.django',

More info could be found in the last paragraph of the first answer to this question: Setting Django up to use MySQL

Hope this helps!!

Embed a PowerPoint presentation into HTML

Some Flash tool that can convert the PowerPoint file to Flash could be helpful. Slide share is also helpful. For me, I will take something like PPT2Flash Pro or things like that.

Dynamic button click event handler

Just to round out Reed's answer, you can either get the Button objects from the Form or other container and add the handler, or you could create the Button objects programmatically.
If you get the Button objects from the Form or other container, then you can iterate over the Controls collection of the Form or other container control, such as Panel or FlowLayoutPanel and so on. You can then just add the click handler with
AddHandler ctrl.Click, AddressOf Me.Button_Click (variables as in the code below),
but I prefer to check the type of the Control and cast to a Button so as I'm not adding click handlers for any other controls in the container (such as Labels). Remember that you can add handlers for any event of the Button at this point using AddHandler.
Alternatively, you can create the Button objects programmatically, as in the second block of code below.
Then, of course, you have to write the handler method, as in the third code block below.

Here is an example using Form as the container, but you're probably better off using a Panel or some other container control.

Dim btn as Button = Nothing
For Each ctrl As Control in myForm.Controls
    If TypeOf ctrl Is Button Then
        btn = DirectCast(ctrl, Button)
        AddHandler btn.Click, AddressOf Me.Button_Click   ' From answer by Reed.
    End If
 Next

Alternatively creating the Buttons programmatically, this time adding to a Panel container.

Dim Panel1 As new Panel()
For i As Integer = 1 to 100
    btn = New Button()
    ' Set Button properties or call a method to do so.
    Panel1.Controls.Add(btn)  ' Add Button to the container.
    AddHandler btn.Click, AddressOf Me.Button_Click   ' Again from the answer by Reed.
Next

Then your handler will look something like this

Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    ' Handle your Button clicks here
End Sub

How to resolve "git did not exit cleanly (exit code 128)" error on TortoiseGit?

It's probably because your SSH key has been removed/revoked. Make a new one and add it to your GitHub account.

global variable for all controller and views

At first, a config file is appropriate for this kind of things but you may also use another approach, which is as given below (Laravel - 4):

// You can keep this in your filters.php file
App::before(function($request) {
    App::singleton('site_settings', function(){
        return Setting::all();
    });

    // If you use this line of code then it'll be available in any view
    // as $site_settings but you may also use app('site_settings') as well
    View::share('site_settings', app('site_settings'));
});

To get the same data in any controller you may use:

$site_settings = app('site_settings');

There are many ways, just use one or another, which one you prefer but I'm using the Container.

AngularJS ng-repeat handle empty list case

And if you want to use this with a filtered list here's a neat trick:

<ul>
    <li ng-repeat="item in filteredItems  = (items | filter:keyword)">
        ...
    </li>
</ul>
<div ng-hide="filteredItems.length">No items found</div>

Laravel Eloquent: Ordering results of all()

You can actually do this within the query.

$results = Project::orderBy('name')->get();

This will return all results with the proper order.

HTML - Display image after selecting filename

Here You Go:

HTML

<!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>
  <input type='file' onchange="readURL(this);" />
    <img id="blah" src="#" alt="your image" />
</body>
</html>

Script:

function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah')
                    .attr('src', e.target.result)
                    .width(150)
                    .height(200);
            };

            reader.readAsDataURL(input.files[0]);
        }
    }

Live Demo

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

For Windows, when you install a package, you type:

python -m pip install [packagename]

How to add a class to a given element?

document.getElementById('some_id').className+='  someclassname'

OR:

document.getElementById('some_id').classList.add('someclassname')

First approach helped in adding the class when second approach didn't work.
Don't forget to keep a space in front of the ' someclassname' in the first approach.

For removal you can use:

document.getElementById('some_id').classList.remove('someclassname')

Append a tuple to a list - what's the difference between two ways?

It has nothing to do with append. tuple(3, 4) all by itself raises that error.

The reason is that, as the error message says, tuple expects an iterable argument. You can make a tuple of the contents of a single object by passing that single object to tuple. You can't make a tuple of two things by passing them as separate arguments.

Just do (3, 4) to make a tuple, as in your first example. There's no reason not to use that simple syntax for writing a tuple.

MySQL: Invalid use of group function

You need to use HAVING, not WHERE.

The difference is: the WHERE clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT function.

HAVING is like WHERE, only it happens after the COUNT value has been computed, so it'll work as you expect. Rewrite your subquery as:

(                  -- where that pid is in the set:
SELECT c2.pid                  -- of pids
FROM Catalog AS c2             -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)

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

Here is another way to do it if you want to use ViewData:

@Html.Partial("~/PathToYourView.cshtml", null, new ViewDataDictionary { { "VariableName", "some value" } })

And to retrieve the passed in values:

@{
    string valuePassedIn = this.ViewData.ContainsKey("VariableName") ? this.ViewData["VariableName"].ToString() : string.Empty;
}

How to get the CUDA version?

We have three ways to check Version: In my case below is the output:- Way 1:-

cat /usr/local/cuda/version.txt

Output:-

CUDA Version 10.1.243

Way2:-

nvcc --version

Output:-

nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2017 NVIDIA Corporation
Built on Fri_Nov__3_21:07:56_CDT_2017
Cuda compilation tools, release 9.1, V9.1.85

Way3:-

/usr/local/cuda/bin/nvcc --version

Output:-

nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2019 NVIDIA Corporation
Built on Sun_Jul_28_19:07:16_PDT_2019
Cuda compilation tools, release 10.1, V10.1.243

Way4:-

nvidia-smi
NVIDIA-SMI 450.36.06    Driver Version: 450.36.06    CUDA Version: 11.0

Outputs are not same. Don't know why it's happening.

TypeError: $(...).DataTable is not a function

Honestly, this took hours to get this fixed. Finally only one thing worked a reconfirmation to solution provided by "Basheer AL-MOMANI". Which is just putting statement

   @RenderSection("scripts", required: false)

within _Layout.cshtml file after all <script></script> elements and also commenting the jquery script in the same file. Secondly, I had to add

 $.noConflict();

within jquery function call at another *.cshtml file as:

 $(document).readyfunction () {
          $.noConflict();
          $("#example1").DataTable();
         $('#example2').DataTable({
              "paging": true,
              "lengthChange": false,
              "searching": false,
              "ordering": true,
              "info": true,
              "autoWidth": false,
          });

        });

Remove all values within one list from another list?

I was looking for fast way to do the subject, so I made some experiments with suggested ways. And I was surprised by results, so I want to share it with you.

Experiments were done using pythonbenchmark tool and with

a = range(1,50000) # Source list
b = range(1,15000) # Items to remove

Results:

 def comprehension(a, b):
     return [x for x in a if x not in b]

5 tries, average time 12.8 sec

def filter_function(a, b):
    return filter(lambda x: x not in b, a)

5 tries, average time 12.6 sec

def modification(a,b):
    for x in b:
        try:
            a.remove(x)
        except ValueError:
            pass
    return a

5 tries, average time 0.27 sec

def set_approach(a,b):
    return list(set(a)-set(b))

5 tries, average time 0.0057 sec

Also I made another measurement with bigger inputs size for the last two functions

a = range(1,500000)
b = range(1,100000)

And the results:

For modification (remove method) - average time is 252 seconds For set approach - average time is 0.75 seconds

So you can see that approach with sets is significantly faster than others. Yes, it doesn't keep similar items, but if you don't need it - it's for you. And there is almost no difference between list comprehension and using filter function. Using 'remove' is ~50 times faster, but it modifies source list. And the best choice is using sets - it's more than 1000 times faster than list comprehension!

How do I force "git pull" to overwrite local files?

Once you do git pull, you will get list of files that are not matching. If the number of files is not very large then you can checkout those files, this action will overwrite those files.

git checkout -- <filename>

I usually do it if for quick check I modify local files on server (no recommended and probabaly reason behind you getting this issue :D ), I checkout the changed files after finding solution.

How to run script as another user without password?

`su -c "Your command right here" -s /bin/sh username`

The above command is correct, but on Red Hat if selinux is enforcing it will not allow cron to execute scripts as another user. example; execl: couldn't exec /bin/sh execl: Permission denied

I had to install setroubleshoot and setools and run the following to allow it:

yum install setroubleshoot setools
sealert -a /var/log/audit/audit.log
grep crond /var/log/audit/audit.log | audit2allow -M mypol
semodule -i mypol.p

.htaccess rewrite to redirect root URL to subdirectory

try to use below lines in htaccess

Note: you may need to check what is the name of the default.html

default.html is the file that load by default in the root folder.

RewriteEngine

Redirect /default.html http://example.com/store/

Permissions error when connecting to EC2 via SSH on Mac OSx

In my case it's because the permission for my home directory is 775, and SSH is not happy about it. It should work after executing:

server$ chmod go-w ~/
server$ chmod 700 ~/.ssh
server$ chmod 600 ~/.ssh/authorized_keys

I had very similar experience this afternoon. I was setting up django on EC2, and suddenly I cannot SSH into the box anymore. Glad I still had an active connection, so I modified /etc/ssh/sshd_config to set:

PasswordAuthentication yes

and set password for ec2-user, then I can login by entering the password.

However, after some googling I found this thread: http://ubuntuforums.org/showthread.php?t=577279. It turned out that during my setup of django I changed the permission for my home directory, and SSH is very strict about this. So the file permission must be set correctly.

How to change max_allowed_packet size

Set the max allowed packet size using MySql Workbench and restart the serverMysql Workbench

ng if with angular for string contains

ES2015 UPDATE

ES2015 have String#includes method that checks whether a string contains another. This can be used if the target environment supports it. The method returns true if the needle is found in haystack else returns false.

ng-if="haystack.includes(needle)"

Here, needle is the string that is to be searched in haystack.

See Browser Compatibility table from MDN. Note that this is not supported by IE and Opera. In this case polyfill can be used.


You can use String#indexOf to get the index of the needle in haystack.

  1. If the needle is not present in the haystack -1 is returned.
  2. If needle is present at the beginning of the haystack 0 is returned.
  3. Else the index at which needle is, is returned.

The index can be compared with -1 to check whether needle is found in haystack.

ng-if="haystack.indexOf(needle) > -1" 

For Angular(2+)

*ngIf="haystack.includes(needle)"

MySQL - How to select data by string length

select * from *tablename* where 1 having length(*fieldname*)=*fieldlength*

Example if you want to select from customer the entry's with a name shorter then 2 chars.

select * from customer where 1 **having length(name)<2**

How to define a Sql Server connection string to use in VB.NET?

Set the connection string in your config file:

<connectionStrings>
    <add name="ConnString"
         connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\gadgetDatabase.mdf;Integrated Security=True" />
</connectionStrings>

Where do I find some good examples for DDD?

.NET DDD Sample from Domain-Driven Design Book by Eric Evans can be found here: http://dddsamplenet.codeplex.com

Cheers,

Jakub G

Java default constructor

When we do not explicitly define a constructor for a class, then java creates a default constructor for the class. It is essentially a non-parameterized constructor, i.e. it doesn't accept any arguments.

The default constructor's job is to call the super class constructor and initialize all instance variables. If the super class constructor is not present then it automatically initializes the instance variables to zero. So, that serves the purpose of using constructor, which is to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object.

Once we define our own constructor for the class, the default constructor is no longer used. So, neither of them is actually a default constructor.

How to send a "multipart/form-data" with requests in python?

You need to use the name attribute of the upload file that is in the HTML of the site. Example:

autocomplete="off" name="image">

You see name="image">? You can find it in the HTML of a site for uploading the file. You need to use it to upload the file with Multipart/form-data

script:

import requests

site = 'https://prnt.sc/upload.php' # the site where you upload the file
filename = 'image.jpg'  # name example

Here, in the place of image, add the name of the upload file in HTML

up = {'image':(filename, open(filename, 'rb'), "multipart/form-data")}

If the upload requires to click the button for upload, you can use like that:

data = {
     "Button" : "Submit",
}

Then start the request

request = requests.post(site, files=up, data=data)

And done, file uploaded succesfully

Add element to a list In Scala

You are using an immutable list. The operations on the List return a new List. The old List remains unchanged. This can be very useful if another class / method holds a reference to the original collection and is relying on it remaining unchanged. You can either use different named vals as in

val myList1 = 1.0 :: 5.5 :: Nil 
val myList2 = 2.2 :: 3.7 :: mylist1

or use a var as in

var myList = 1.0 :: 5.5 :: Nil 
myList :::= List(2.2, 3.7)

This is equivalent syntax for:

myList = myList.:::(List(2.2, 3.7))

Or you could use one of the mutable collections such as

val myList = scala.collection.mutable.MutableList(1.0, 5.5)
myList.++=(List(2.2, 3.7))

Not to be confused with the following that does not modify the original mutable List, but returns a new value:

myList.++:(List(2.2, 3.7))

However you should only use mutable collections in performance critical code. Immutable collections are much easier to reason about and use. One big advantage is that immutable List and scala.collection.immutable.Vector are Covariant. Don't worry if that doesn't mean anything to you yet. The advantage of it is you can use it without fully understanding it. Hence the collection you were using by default is actually scala.collection.immutable.List its just imported for you automatically.

I tend to use List as my default collection. From 2.12.6 Seq defaults to immutable Seq prior to this it defaulted to immutable.

How do I build JSON dynamically in javascript?

As myJSON is an object you can just set its properties, for example:

myJSON.list1 = ["1","2"];

If you dont know the name of the properties, you have to use the array access syntax:

myJSON['list'+listnum] = ["1","2"];

If you want to add an element to one of the properties, you can do;

myJSON.list1.push("3");

Fastest way to convert an iterator to a list

@Robino was suggesting to add some tests which make sense, so here is a simple benchmark between 3 possible ways (maybe the most used ones) to convert an iterator to a list:

  1. by type constructor

list(my_iterator)

  1. by unpacking

[*my_iterator]

  1. using list comprehension

[e for e in my_iterator]

I have been using simple_bechmark library

from simple_benchmark import BenchmarkBuilder
from heapq import nsmallest

b = BenchmarkBuilder()

@b.add_function()
def convert_by_type_constructor(size):
    list(iter(range(size)))

@b.add_function()
def convert_by_list_comprehension(size):
    [e for e in iter(range(size))]

@b.add_function()
def convert_by_unpacking(size):
    [*iter(range(size))]


@b.add_arguments('Convert an iterator to a list')
def argument_provider():
    for exp in range(2, 22):
        size = 2**exp
        yield size, size

r = b.run()
r.plot()

enter image description here

As you can see there is very hard to make a difference between conversion by the constructor and conversion by unpacking, conversion by list comprehension is the “slowest” approach.


I have been testing also across different Python versions (3.6, 3.7, 3.8, 3.9) by using the following simple script:

import argparse
import timeit

parser = argparse.ArgumentParser(
    description='Test convert iterator to list')
parser.add_argument(
    '--size', help='The number of elements from iterator')

args = parser.parse_args()

size = int(args.size)
repeat_number = 10000

# do not wait too much if the size is too big
if size > 10000:
    repeat_number = 100


def test_convert_by_type_constructor():
    list(iter(range(size)))


def test_convert_by_list_comprehension():
    [e for e in iter(range(size))]


def test_convert_by_unpacking():
    [*iter(range(size))]


def get_avg_time_in_ms(func):
    avg_time = timeit.timeit(func, number=repeat_number) * 1000 / repeat_number
    return round(avg_time, 6)


funcs = [test_convert_by_type_constructor,
         test_convert_by_unpacking, test_convert_by_list_comprehension]

print(*map(get_avg_time_in_ms, funcs))

The script will be executed via a subprocess from a Jupyter Notebook (or a script), the size parameter will be passed through command-line arguments and the script results will be taken from standard output.

from subprocess import PIPE, run

import pandas

simple_data = {'constructor': [], 'unpacking': [], 'comprehension': [],
        'size': [], 'python version': []}


size_test = 100, 1000, 10_000, 100_000, 1_000_000
for version in ['3.6', '3.7', '3.8', '3.9']:
    print('test for python', version)
    for size in size_test:
        command = [f'python{version}', 'perf_test_convert_iterator.py', f'--size={size}']
        result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
        constructor, unpacking,  comprehension = result.stdout.split()
        
        simple_data['constructor'].append(float(constructor))
        simple_data['unpacking'].append(float(unpacking))
        simple_data['comprehension'].append(float(comprehension))
        simple_data['python version'].append(version)
        simple_data['size'].append(size)

df_ = pandas.DataFrame(simple_data)
df_

enter image description here

You can get my full notebook from here.

In most of the cases, in my tests, unpacking shows to be faster, but the difference is so small that the results may change from a run to the other. Again, the comprehension approach is the slowest, in fact, the other 2 methods are up to ~ 60% faster.

Should I initialize variable within constructor or outside constructor

One thing, regardless of how you initialize the field, use of the final qualifier, if possible, will ensure the visibility of the field's value in a multi-threaded environment.

How to send Request payload to REST API in java?

I tried with a rest client.

Headers :

  • POST /r/gerrit/rpc/ChangeDetailService HTTP/1.1
  • Host: git.eclipse.org
  • User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0
  • Accept: application/json
  • Accept-Language: null
  • Accept-Encoding: gzip,deflate,sdch
  • accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
  • Content-Type: application/json; charset=UTF-8
  • Content-Length: 73
  • Connection: keep-alive

it works fine. I retrieve 200 OK with a good body.

Why do you set a status code in your request? and multiple declaration "Accept" with Accept:application/json,application/json,application/jsonrequest. just a statement is enough.

Are PHP short tags acceptable to use?

Convert <? (without a trailing space) to <?php (with a trailing space):

find . -name "*.php" -print0 | xargs -0 perl -pi -e 's/<\?(?!php|=|xml|mso| )/<\?php /g'

Convert <? (with a trailing space) to <?php (retaining the trailing space):

find . -name "*.php" -print0 | xargs -0 perl -pi -e 's/<\? /<\?php /g'

Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?

    >>import pandas as pd
    >>import numpy as np
    >>data.shape
    (480,193)
    >>type(data)
    numpy.ndarray
    >>df=pd.DataFrame(data=data[0:,0:],
    ...        index=[i for i in range(data.shape[0])],
    ...        columns=['f'+str(i) for i in range(data.shape[1])])
    >>df.head()
    [![array to dataframe][1]][1]

enter image description here

php, mysql - Too many connections to database error

The error SQLSTATE[HY000] [1040] Too many connections is an SQL error, and has to do with the sql server. There could be other applications connecting to the server. The server has a maximum available connections number.

If you have phpmyadmin, you can use the 'variables' tab to check what the setting is.

You can also query the status table like so:

show status like '%onn%';

Or some variance on that. check the manual for what variables there are

(be aware, 'connections' is not the current connections, check that link :) )

What is the Swift equivalent of respondsToSelector?

It seems you need to define your protocol as as subprotocol of NSObjectProtocol ... then you'll get respondsToSelector method

@objc protocol YourDelegate : NSObjectProtocol
{
    func yourDelegateMethod(passObject: SomeObject)
}

note that only specifying @objc was not enough. You should be also careful that the actual delegate is a subclass of NSObject - which in Swift might not be.

Input type "number" won't resize

Incorrect usage.

Input type number it's made to have selectable value via arrows up and down.

So basically you are looking for "width" CSS style.

Input text historically is formatted with monospaced font, so size it's also the width it takes.

Input number it's new and "size" property has no sense at all*. A typical usage:

<input type="number" name="quantity" min="1" max="5">

w3c docs

to fix, add a style:

<input type="number" name="email" style="width: 7em">

EDIT: if you want a range, you have to set type="range" and not ="number"

EDIT2: *size is not an allowed value (so, no sense). Check out official W3C specifications

Note: The size attribute works with the following input types: text, search, tel, url, email, and password.

Tip: To specify the maximum number of characters allowed in the element, use the maxlength attribute.

Bootstrap footer at the bottom of the page

In my case for Bootstrap4:

<body class="d-flex flex-column min-vh-100">
    <div class="wrapper flex-grow-1"></div>
    <footer></footer>
</body>

Connecting an input stream to an outputstream

Asynchronous way to achieve it.

void inputStreamToOutputStream(final InputStream inputStream, final OutputStream out) {
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                int d;
                while ((d = inputStream.read()) != -1) {
                    out.write(d);
                }
            } catch (IOException ex) {
                //TODO make a callback on exception.
            }
        }
    });
    t.setDaemon(true);
    t.start();
}

What's the reason I can't create generic array types in Java?

Arrays Are Covariant

Arrays are said to be covariant which basically means that, given the subtyping rules of Java, an array of type T[] may contain elements of type T or any subtype of T. For instance

Number[] numbers = new Number[3];
numbers[0] = newInteger(10);
numbers[1] = newDouble(3.14);
numbers[2] = newByte(0);

But not only that, the subtyping rules of Java also state that an array S[] is a subtype of the array T[] if S is a subtype of T, therefore, something like this is also valid:

Integer[] myInts = {1,2,3,4};
Number[] myNumber = myInts;

Because according to the subtyping rules in Java, an array Integer[] is a subtype of an array Number[] because Integer is a subtype of Number.

But this subtyping rule can lead to an interesting question: what would happen if we try to do this?

myNumber[0] = 3.14; //attempt of heap pollution

This last line would compile just fine, but if we run this code, we would get an ArrayStoreException because we’re trying to put a double into an integer array. The fact that we are accessing the array through a Number reference is irrelevant here, what matters is that the array is an array of integers.

This means that we can fool the compiler, but we cannot fool the run-time type system. And this is so because arrays are what we call a reifiable type. This means that at run-time Java knows that this array was actually instantiated as an array of integers which simply happens to be accessed through a reference of type Number[].

So, as we can see, one thing is the actual type of the object, an another thing is the type of the reference that we use to access it, right?

The Problem with Java Generics

Now, the problem with generic types in Java is that the type information for type parameters is discarded by the compiler after the compilation of code is done; therefore this type information is not available at run time. This process is called type erasure. There are good reasons for implementing generics like this in Java, but that’s a long story, and it has to do with binary compatibility with pre-existing code.

The important point here is that since at run-time there is no type information, there is no way to ensure that we are not committing heap pollution.

Let’s consider now the following unsafe code:

List<Integer> myInts = newArrayList<Integer>();
myInts.add(1);
myInts.add(2);
List<Number> myNums = myInts; //compiler error
myNums.add(3.14); //heap polution

If the Java compiler does not stop us from doing this, the run-time type system cannot stop us either, because there is no way, at run time, to determine that this list was supposed to be a list of integers only. The Java run-time would let us put whatever we want into this list, when it should only contain integers, because when it was created, it was declared as a list of integers. That’s why the compiler rejects line number 4 because it is unsafe and if allowed could break the assumptions of the type system.

As such, the designers of Java made sure that we cannot fool the compiler. If we cannot fool the compiler (as we can do with arrays) then we cannot fool the run-time type system either.

As such, we say that generic types are non-reifiable, since at run time we cannot determine the true nature of the generic type.

I skipped some parts of this answers you can read full article here: https://dzone.com/articles/covariance-and-contravariance

Set QLineEdit to accept only numbers

You could also set an inputMask:

QLineEdit.setInputMask("9")

This allows the user to type only one digit ranging from 0 to 9. Use multiple 9's to allow the user to enter multiple numbers. See also the complete list of characters that can be used in an input mask.

(My answer is in Python, but it should not be hard to transform it to C++)

Show or hide element in React

React circa 2020

In the onClick callback, call the state hook's setter function to update the state and re-render:

_x000D_
_x000D_
const Search = () => {_x000D_
  const [showResults, setShowResults] = React.useState(false)_x000D_
  const onClick = () => setShowResults(true)_x000D_
  return (_x000D_
    <div>_x000D_
      <input type="submit" value="Search" onClick={onClick} />_x000D_
      { showResults ? <Results /> : null }_x000D_
    </div>_x000D_
  )_x000D_
}_x000D_
_x000D_
const Results = () => (_x000D_
  <div id="results" className="search-results">_x000D_
    Some Results_x000D_
  </div>_x000D_
)_x000D_
_x000D_
ReactDOM.render(<Search />, document.querySelector("#container"))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>_x000D_
_x000D_
<div id="container">_x000D_
  <!-- This element's contents will be replaced with your component. -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

JSFiddle

React circa 2014

The key is to update the state of the component in the click handler using setState. When the state changes get applied, the render method gets called again with the new state:

_x000D_
_x000D_
var Search = React.createClass({_x000D_
    getInitialState: function() {_x000D_
        return { showResults: false };_x000D_
    },_x000D_
    onClick: function() {_x000D_
        this.setState({ showResults: true });_x000D_
    },_x000D_
    render: function() {_x000D_
        return (_x000D_
            <div>_x000D_
                <input type="submit" value="Search" onClick={this.onClick} />_x000D_
                { this.state.showResults ? <Results /> : null }_x000D_
            </div>_x000D_
        );_x000D_
    }_x000D_
});_x000D_
_x000D_
var Results = React.createClass({_x000D_
    render: function() {_x000D_
        return (_x000D_
            <div id="results" className="search-results">_x000D_
                Some Results_x000D_
            </div>_x000D_
        );_x000D_
    }_x000D_
});_x000D_
_x000D_
ReactDOM.render( <Search /> , document.getElementById('container'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.min.js"></script>_x000D_
_x000D_
<div id="container">_x000D_
  <!-- This element's contents will be replaced with your component. -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

JSFiddle

MySQL - SELECT all columns WHERE one column is DISTINCT

SELECT DISTINCT link,id,day,month FROM posted WHERE ad='$key' ORDER BY day, month

OR

SELECT link,id,day,month FROM posted WHERE ad='$key' ORDER BY day, month

CORS - How do 'preflight' an httprequest?

Although this thread dates back to 2014, the issue can still be current to many of us. Here is how I dealt with it in a jQuery 1.12 /PHP 5.6 context:

  • jQuery sent its XHR request using only limited headers; only 'Origin' was sent.
  • No preflight request was needed.
  • The server only had to detect such a request, and add the "Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN'] header, after detecting that this was a cross-origin XHR.

PHP Code sample:

if (!empty($_SERVER['HTTP_ORIGIN'])) {
    // Uh oh, this XHR comes from outer space...
    // Use this opportunity to filter out referers that shouldn't be allowed to see this request
    if (!preg_match('@\.partner\.domain\.net$@'))
        die("End of the road if you're not my business partner.");

    // otherwise oblige
    header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
}
else {
    // local request, no need to send a specific header for CORS
}

In particular, don't add an exit; as no preflight is needed.

How to list all Git tags?

For a GUI to do this I have just found that 'gitk' supports named views. The views have several options for selecting commits. One handy one is a box for selecting "All tags". That seems to work for me to see the tags.

How to detect scroll position of page using jQuery

$(window).scroll( function() { 
 var scrolled_val = $(document).scrollTop().valueOf();
 alert(scrolled_val+ ' = scroll value');
});

This is another way of getting the value of scroll.

Should 'using' directives be inside or outside the namespace?

According the to StyleCop Documentation:

SA1200: UsingDirectivesMustBePlacedWithinNamespace

Cause A C# using directive is placed outside of a namespace element.

Rule Description A violation of this rule occurs when a using directive or a using-alias directive is placed outside of a namespace element, unless the file does not contain any namespace elements.

For example, the following code would result in two violations of this rule.

using System;
using Guid = System.Guid;

namespace Microsoft.Sample
{
    public class Program
    {
    }
}

The following code, however, would not result in any violations of this rule:

namespace Microsoft.Sample
{
    using System;
    using Guid = System.Guid;

    public class Program
    {
    }
}

This code will compile cleanly, without any compiler errors. However, it is unclear which version of the Guid type is being allocated. If the using directive is moved inside of the namespace, as shown below, a compiler error will occur:

namespace Microsoft.Sample
{
    using Guid = System.Guid;
    public class Guid
    {
        public Guid(string s)
        {
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            Guid g = new Guid("hello");
        }
    }
}

The code fails on the following compiler error, found on the line containing Guid g = new Guid("hello");

CS0576: Namespace 'Microsoft.Sample' contains a definition conflicting with alias 'Guid'

The code creates an alias to the System.Guid type called Guid, and also creates its own type called Guid with a matching constructor interface. Later, the code creates an instance of the type Guid. To create this instance, the compiler must choose between the two different definitions of Guid. When the using-alias directive is placed outside of the namespace element, the compiler will choose the local definition of Guid defined within the local namespace, and completely ignore the using-alias directive defined outside of the namespace. This, unfortunately, is not obvious when reading the code.

When the using-alias directive is positioned within the namespace, however, the compiler has to choose between two different, conflicting Guid types both defined within the same namespace. Both of these types provide a matching constructor. The compiler is unable to make a decision, so it flags the compiler error.

Placing the using-alias directive outside of the namespace is a bad practice because it can lead to confusion in situations such as this, where it is not obvious which version of the type is actually being used. This can potentially lead to a bug which might be difficult to diagnose.

Placing using-alias directives within the namespace element eliminates this as a source of bugs.

  1. Multiple Namespaces

Placing multiple namespace elements within a single file is generally a bad idea, but if and when this is done, it is a good idea to place all using directives within each of the namespace elements, rather than globally at the top of the file. This will scope the namespaces tightly, and will also help to avoid the kind of behavior described above.

It is important to note that when code has been written with using directives placed outside of the namespace, care should be taken when moving these directives within the namespace, to ensure that this is not changing the semantics of the code. As explained above, placing using-alias directives within the namespace element allows the compiler to choose between conflicting types in ways that will not happen when the directives are placed outside of the namespace.

How to Fix Violations To fix a violation of this rule, move all using directives and using-alias directives within the namespace element.

Can jQuery get all CSS styles associated with an element?

@marknadal's solution wasn't grabbing hyphenated properties for me (e.g. max-width), but changing the first for loop in css2json() made it work, and I suspect performs fewer iterations:

for (var i = 0; i < css.length; i += 1) {
    s[css[i]] = css.getPropertyValue(css[i]);
}

Loops via length rather than in, retrieves via getPropertyValue() rather than toLowerCase().

Get my phone number in android

Robi Code is work for me, just put if !null so that if phone number is null, user can fill the phone number by him/her self.

editTextPhoneNumber = (EditText) findViewById(R.id.editTextPhoneNumber);
TelephonyManager tMgr;
tMgr= (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
if (mPhoneNumber != null){
editTextPhoneNumber.setText(mPhoneNumber);
}

How to get image size (height & width) using JavaScript?

Simply, you can test like this.

  <script>
  (function($) {
        $(document).ready(function() {
            console.log("ready....");
            var i = 0;
            var img;
            for(i=1; i<13; i++) {
                img = new Image();
                img.src = 'img/' + i + '.jpg';
                console.log("name : " + img.src);
                img.onload = function() {
                    if(this.height > this.width) {
                        console.log(this.src + " : portrait");
                    }
                    else if(this.width > this.height) {
                        console.log(this.src + " : landscape");
                    }
                    else {
                        console.log(this.src + " : square");
                    }
                }
            }
        });
    }(jQuery));
  </script>

How do I format a date as ISO 8601 in moment.js?

moment().toISOString(); // or format() - see below

http://momentjs.com/docs/#/displaying/as-iso-string/

Update Based on the answer: by @sennet and the comment by @dvlsg (see Fiddle) it should be noted that there is a difference between format and toISOString. Both are correct but the underlying process differs. toISOString converts to a Date object, sets to UTC then uses the native Date prototype function to output ISO8601 in UTC with milliseconds (YYYY-MM-DD[T]HH:mm:ss.SSS[Z]). On the other hand, format uses the default format (YYYY-MM-DDTHH:mm:ssZ) without milliseconds and maintains the timezone offset.

I've opened an issue as I think it can lead to unexpected results.

What is the difference between a var and val definition in Scala?

val is final, that is, cannot be set. Think final in java.

How to check if std::map contains a key without doing insert?

Use my_map.count( key ); it can only return 0 or 1, which is essentially the Boolean result you want.

Alternately my_map.find( key ) != my_map.end() works too.

Get list of Excel files in a folder using VBA

Regarding the upvoted answer, I liked it except that if the resulting "listfiles" array is used in an array formula {CSE}, the list values come out all in a horizontal row. To make them come out in a vertical column, I simply made the array two dimensional as follows:

ReDim vaArray(1 To oFiles.Count, 0)
i = 1
For Each oFile In oFiles
    vaArray(i, 0) = oFile.Name
    i = i + 1
Next

.NET console application as Windows service

So here's the complete walkthrough:

  1. Create new Console Application project (e.g. MyService)
  2. Add two library references: System.ServiceProcess and System.Configuration.Install
  3. Add the three files printed below
  4. Build the project and run "InstallUtil.exe c:\path\to\MyService.exe"
  5. Now you should see MyService on the service list (run services.msc)

*InstallUtil.exe can be usually found here: C:\windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.ex??e

Program.cs

using System;
using System.IO;
using System.ServiceProcess;

namespace MyService
{
    class Program
    {
        public const string ServiceName = "MyService";

        static void Main(string[] args)
        {
            if (Environment.UserInteractive)
            {
                // running as console app
                Start(args);

                Console.WriteLine("Press any key to stop...");
                Console.ReadKey(true);

                Stop();
            }
            else
            {
                // running as service
                using (var service = new Service())
                {
                    ServiceBase.Run(service);
                }
            }
        }

        public static void Start(string[] args)
        {
            File.AppendAllText(@"c:\temp\MyService.txt", String.Format("{0} started{1}", DateTime.Now, Environment.NewLine));
        }

        public static void Stop()
        {
            File.AppendAllText(@"c:\temp\MyService.txt", String.Format("{0} stopped{1}", DateTime.Now, Environment.NewLine));
        }
    }
}

MyService.cs

using System.ServiceProcess;

namespace MyService
{
    class Service : ServiceBase
    {
        public Service()
        {
            ServiceName = Program.ServiceName;
        }

        protected override void OnStart(string[] args)
        {
            Program.Start(args);
        }

        protected override void OnStop()
        {
            Program.Stop();
        }
    }
}

MyServiceInstaller.cs

using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;

namespace MyService
{
    [RunInstaller(true)]
    public class MyServiceInstaller : Installer
    {
        public MyServiceInstaller()
        {
            var spi = new ServiceProcessInstaller();
            var si = new ServiceInstaller();

            spi.Account = ServiceAccount.LocalSystem;
            spi.Username = null;
            spi.Password = null;

            si.DisplayName = Program.ServiceName;
            si.ServiceName = Program.ServiceName;
            si.StartType = ServiceStartMode.Automatic;

            Installers.Add(spi);
            Installers.Add(si);
        }
    }
}

Raw SQL Query without DbSet - Entity Framework Core

My case used stored procedure instead of raw SQL

Created a class

Public class School
{
    [Key]
    public Guid SchoolId { get; set; }
    public string Name { get; set; }
    public string Branch { get; set; }
    public int NumberOfStudents  { get; set; }
}

Added below on my DbContext class

public DbSet<School> SP_Schools { get; set; }

To execute the stored procedure:

var MySchools = _db.SP_Schools.FromSqlRaw("GetSchools @schoolId, @page, @size ",
              new SqlParameter("schoolId", schoolId),
              new SqlParameter("page", page),
              new SqlParameter("size", size)))
.IgnoreQueryFilters();

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

If you transferred these files through disk or other means, it is likely they were not saved properly.

How to avoid Python/Pandas creating an index in a saved csv?

If you want a good format the next statement is the best:

dataframe_prediction.to_csv('filename.csv', sep=',', encoding='utf-8', index=False)

In this case you have got a csv file with ',' as separate between columns and utf-8 format. In addition, numerical index won't appear.

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

You can use javascript:void(0) here instead of using # to stop anchor tag redirect to header section.

function helloFunction() {
    alert("hello world");
}
<a href="javascript:void(0)" onclick="helloFunction();">Call Hello Function</a>

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

Save bitmap to file function

Here is the function which help you

private void saveBitmap(Bitmap bitmap,String path){
        if(bitmap!=null){
            try {
                FileOutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(path); //here is set your file path where you want to save or also here you can set file object directly

                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); // bitmap is your Bitmap instance, if you want to compress it you can compress reduce percentage
                    // PNG is a lossless format, the compression factor (100) is ignored
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (outputStream != null) {
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }    
        }
    }

JPA Hibernate One-to-One relationship

This should be working too using JPA 2.0 @MapsId annotation instead of Hibernate's GenericGenerator:

@Entity
public class Person {

    @Id
    @GeneratedValue
    public int id;

    @OneToOne
    @PrimaryKeyJoinColumn
    public OtherInfo otherInfo;

    rest of attributes ...
}

@Entity
public class OtherInfo {

    @Id
    public int id;

    @MapsId
    @OneToOne
    @JoinColumn(name="id")
    public Person person;

    rest of attributes ...
}

More details on this in Hibernate 4.1 documentation under section 5.1.2.2.7.

How to use setInterval and clearInterval?

I used angular with electron,

In my case, setInterval returns a Nodejs Timer object. which when I called clearInterval(timerobject) it did not work.

I had to get the id first and call to clearInterval

clearInterval(timerobject._id)

I have struggled many hours with this. hope this helps.

How do you get the Git repository's name in some Git repository?

Here's a bash function that will print the repository name (if it has been properly set up):

__get_reponame ()
{
    local gitdir=$(git rev-parse --git-dir)

    if [ $(cat ${gitdir}/description) != "Unnamed repository; edit this file 'description' to name the repository." ]; then
        cat ${gitdir}/description
    else
        echo "Unnamed repository!"
    fi
}

Explanation:

local gitdir=$(git rev-parse --git-dir)

This executes git rev-parse --git-dir, which prints the full path to the .git directory of the currrent repository. It stores the path in $gitdir.

if [ $(cat ${gitdir}/description) != "..." ]; then

This executes cat ${gitdir}/description, which prints the contents of the .git/description of your current repository. If you've properly named your repository, it will print a name. Otherwise, it will print Unnamed repository; edit this file 'description' to name the repository.

cat ${gitdir}/description

If the repo was properly named, then print the contents.

else

Otherwise...

echo "Unnamed repository!"

Tell the user that the repo was unnamed.


Something similar is implemented in this script.

Converting dict to OrderedDict

You can create the ordered dict from old dict in one line:

from collections import OrderedDict
ordered_dict = OrderedDict(sorted(ship.items())

The default sorting key is by dictionary key, so the new ordered_dict is sorted by old dict's keys.

what is the difference between GROUP BY and ORDER BY in sql

  1. GROUP BY will aggregate records by the specified column which allows you to perform aggregation functions on non-grouped columns (such as SUM, COUNT, AVG, etc.). ORDER BY alters the order in which items are returned.
  2. If you do SELECT IsActive, COUNT(*) FROM Customers GROUP BY IsActive you get a count of active and inactive customers. The group by aggregated the results based on the field you specified. If you do SELECT * FROM Customers ORDER BY Name then you get the result list sorted by the customer’s name.
  3. If you GROUP, the results are not necessarily sorted; although in many cases they may come out in an intuitive order, that's not guaranteed by the GROUP clause. If you want your groups sorted, always use an explicitly ORDER BY after the GROUP BY.
  4. Grouped data cannot be filtered by WHERE clause. Order data can be filtered by WHERE clause.

How to Change Font Size in drawString Java

I've an image located at here, Using below code. I am able to contgrol any things on the text that i wanted to write (Eg,signature,Transparent Water mark, Text with differnt Font and size).

 import java.awt.Font;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.font.TextAttribute;
    import java.awt.image.BufferedImage;
    import java.io.ByteArrayOutputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.net.URL;
    import java.util.HashMap;
    import java.util.Map;

    import javax.imageio.ImageIO;

    public class ImagingTest {

        public static void main(String[] args) throws IOException {
            String url = "http://images.all-free-download.com/images/graphiclarge/bay_beach_coast_coastline_landscape_nature_nobody_601234.jpg";
            String text = "I am appending This text!";
            byte[] b = mergeImageAndText(url, text, new Point(100, 100));
            FileOutputStream fos = new FileOutputStream("so2.png");
            fos.write(b);
            fos.close();
        }

        public static byte[] mergeImageAndText(String imageFilePath,
                String text, Point textPosition) throws IOException {
            BufferedImage im = ImageIO.read(new URL(imageFilePath));
            Graphics2D g2 = im.createGraphics();
            Font currentFont = g2.getFont();
            Font newFont = currentFont.deriveFont(currentFont.getSize() * 1.4F);
            g2.setFont(newFont);


            Map<TextAttribute, Object> attributes = new HashMap<>();

            attributes.put(TextAttribute.FAMILY, currentFont.getFamily());
            attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD);
            attributes.put(TextAttribute.SIZE, (int) (currentFont.getSize() * 2.8));
            newFont = Font.getFont(attributes);

            g2.setFont(newFont);
            g2.drawString(text, textPosition.x, textPosition.y);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(im, "png", baos);
            return baos.toByteArray();
        }
    }

C# : changing listbox row color?

Once you've added your listbox item to your form, change DrawMode with OwnerDrawFixed option from the Properties panel. If you forget to do this, none of the codes below will work. Then click DrawItem event from the Events area.

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
   // 1. Get the item
   string selectedItem = listBox1.Items[e.Index].ToString();
                    
   // 2. Choose font 
   Font font = new Font("Arial", 12);
        
   // 3. Choose colour
   SolidBrush solidBrush = new SolidBrush(Color.Red);
        
   // 4. Get bounds
   int left = e.Bounds.Left;
   int top = e.Bounds.Top;
                    
   // 5. Use Draw the background within the bounds
   e.DrawBackground();
        
   // 6. Colorize listbox items
   e.Graphics.DrawString(selectedItem, font, solidBrush, left, top);
}

sqlplus how to find details of the currently connected database session

Take a look at this one (c) Tanel Poder. You may either run it from your glogin.sql (so these settings will update each time you connect, or just run it manually. Notice host title command - it changes your sql*plus console window title with session information - extremely useful with many windows open simultaneously.

-- the Who am I script

def   mysid="NA"
def _i_spid="NA"
def _i_cpid="NA"
def _i_opid="NA"
def _i_serial="NA"
def _i_inst="NA"
def _i_host="NA"
def _i_user="&_user"
def _i_conn="&_connect_identifier"

col i_username head USERNAME for a20
col i_sid head SID for a5 new_value mysid
col i_serial head SERIAL# for a8 new_value _i_serial
col i_cpid head CPID for a15 new_value _i_cpid
col i_spid head SPID for a15 new_value _i_spid
col i_opid head OPID for a5 new_value _i_opid
col i_host_name head HOST_NAME for a25 new_value _i_host
col i_instance_name head INST_NAME for a12 new_value _i_inst
col i_ver head VERSION for a10
col i_startup_day head STARTED for a8
col _i_user noprint new_value _i_user
col _i_conn noprint new_value _i_conn
col i_myoraver noprint new_value myoraver

select 
    s.username          i_username, 
    i.instance_name i_instance_name, 
    i.host_name         i_host_name, 
    to_char(s.sid)          i_sid, 
    to_char(s.serial#)      i_serial, 
    (select substr(banner, instr(banner, 'Release ')+8,10) from v$version where rownum = 1) i_ver,
    (select  substr(substr(banner, instr(banner, 'Release ')+8),
            1,
            instr(substr(banner, instr(banner, 'Release ')+8),'.')-1)
     from v$version 
     where rownum = 1) i_myoraver,
    to_char(startup_time, 'YYYYMMDD') i_startup_day, 
    p.spid              i_spid, 
    trim(to_char(p.pid))        i_opid, 
    s.process           i_cpid, 
    s.saddr             saddr, 
    p.addr              paddr,
    lower(s.username) "_i_user",
    upper('&_connect_identifier') "_i_conn"
from 
    v$session s, 
    v$instance i, 
    v$process p
where 
    s.paddr = p.addr
and 
    sid = (select sid from v$mystat where rownum = 1);

-- Windows CMD.exe specific stuff

-- host title %CP% &_i_user@&_i_conn [sid=&mysid ser#=&_i_serial spid=&_i_spid inst=&_i_inst host=&_i_host cpid=&_i_cpid opid=&_i_opid]
   host title %CP% &_i_user@&_i_conn [sid=&mysid #=&_i_serial]
-- host doskey /exename=sqlplus.exe desc=set lines 80 sqlprompt ""$Tdescribe $*$Tset lines 299 sqlprompt "SQL> "

-- short xterm title
-- host echo -ne "\033]0;&_i_user@&_i_inst &mysid[&_i_spid]\007"
-- long xterm title
--host echo -ne "\033]0;host=&_i_host inst=&_i_inst sid=&mysid ser#=&_i_serial spid=&_i_spid cpid=&_i_cpid opid=&_i_opid\007"


def myopid=&_i_opid
def myspid=&_i_spid
def mycpid=&_i_cpid

-- undef _i_spid _i_inst _i_host _i_user _i_conn _i_cpid

Sample output:

17:39:35 SYSTEM@saz-dev> @sandbox
Connected.
18:29:02 SYSTEM@sandbox> @me

USERNAME             INST_NAME    HOST_NAME                 SID   SERIAL#  VERSION    STARTED  SPID            OPID  CPID            SADDR    PADDR
-------------------- ------------ ------------------------- ----- -------- ---------- -------- --------------- ----- --------------- -------- --------
SYSTEM               xe           OARS-SANDBOX              34    175      11.2.0.2.0 20130318 3348            30    6108:7776       6F549590 6FF51020

1 row selected.

Elapsed: 00:00:00.04

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

You may be interested in the Unicode categories "Other, Control" and possibly "Other, Format" (unfortunately the latter seems to contain both unprintable and printable characters).

In Java regular expressions you can check for them using \p{Cc} and \p{Cf} respectively.

Attaching click to anchor tag in angular

You can use routerLink (which is an alternative of href for angular 2+) with click event as below to prevent from page reloading

<a [routerLink]="" (click)="onGoToPage2()">Go to page</a>

Why I can't change directories using "cd"?

Note the discussion How do I set the working directory of the parent process?

It contains some hackish answers, e.g. https://stackoverflow.com/a/2375174/755804 (changing the parent process directory via gdb, don't do this) and https://stackoverflow.com/a/51985735/755804 (the command tailcd that injects cd dirname to the input stream of the parent process; well, ideally it should be a part of bash rather than a hack)

Using setTimeout to delay timing of jQuery actions

.html() only takes a string OR a function as an argument, not both. Try this:

 $("#showDiv").click(function () {
     $('#theDiv').show(1000, function () {
         setTimeout(function () {
             $('#theDiv').html(function () {
                 setTimeout(function () {
                     $('#theDiv').html('Here is some replacement text');
                 }, 0);
                 setTimeout(function () {
                     $('#theDiv').html('More replacement text goes here');
                 }, 2500);
             });
         }, 2500);
     });
 }); //click function ends

jsFiddle example

Django URL Redirect

You can try the Class Based View called RedirectView

from django.views.generic.base import RedirectView

urlpatterns = patterns('',
    url(r'^$', 'macmonster.views.home'),
    #url(r'^macmon_home$', 'macmonster.views.home'),
    url(r'^macmon_output/$', 'macmonster.views.output'),
    url(r'^macmon_about/$', 'macmonster.views.about'),
    url(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')
)

Notice how as url in the <url_to_home_view> you need to actually specify the url.

permanent=False will return HTTP 302, while permanent=True will return HTTP 301.

Alternatively you can use django.shortcuts.redirect

Update for Django 2+ versions

With Django 2+, url() is deprecated and replaced by re_path(). Usage is exactly the same as url() with regular expressions. For replacements without the need of regular expression, use path().

from django.urls import re_path

re_path(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')

Force table column widths to always be fixed regardless of contents

You can also work with "overflow: hidden" or "overflow-x: hidden" (for just the width). This requires a defined width (and/or height?) and maybe a "display: block" as well.

"Overflow:Hidden" hides the whole content, which does not fit into the defined box.

Example:

http://jsfiddle.net/NAJvp/

HTML:

<table border="1">
    <tr>
        <td><div>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</div></td>
        <td>bbb</td>
        <td>cccc</td>
    </tr>
</table>

CSS:

td div { width: 100px; overflow-y: hidden; }

EDIT: Shame on me, I've seen, you already use "overflow". I guess it doesn't work, because you don't set "display: block" to your element ...

Why isn't my Pandas 'apply' function referencing multiple columns working?

Let's say we want to apply a function add5 to columns 'a' and 'b' of DataFrame df

def add5(x):
    return x+5

df[['a', 'b']].apply(add5)

How to write to a file, using the logging Python module?

import sys
import logging

from util import reducer_logfile
logging.basicConfig(filename=reducer_logfile, format='%(message)s',
                    level=logging.INFO, filemode='w')

How do you specify a byte literal in Java?

With Java 7 and later version, you can specify a byte literal in this way: byte aByte = (byte)0b00100001;

Reference: http://docs.oracle.com/javase/8/docs/technotes/guides/language/binary-literals.html

What are the rules for calling the superclass constructor?

CDerived::CDerived()
: CBase(...), iCount(0)  //this is the initialisation list. You can initialise member variables here too. (e.g. iCount := 0)
    {
    //construct body
    }

only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

I believe your problem is this: in your while loop, n is divided by 2, but never cast as an integer again, so it becomes a float at some point. It is then added onto y, which is then a float too, and that gives you the warning.

Java - How to find the redirected url of a url?

public static URL getFinalURL(URL url) {
    try {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setInstanceFollowRedirects(false);
        con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
        con.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
        con.addRequestProperty("Referer", "https://www.google.com/");
        con.connect();
        //con.getInputStream();
        int resCode = con.getResponseCode();
        if (resCode == HttpURLConnection.HTTP_SEE_OTHER
                || resCode == HttpURLConnection.HTTP_MOVED_PERM
                || resCode == HttpURLConnection.HTTP_MOVED_TEMP) {
            String Location = con.getHeaderField("Location");
            if (Location.startsWith("/")) {
                Location = url.getProtocol() + "://" + url.getHost() + Location;
            }
            return getFinalURL(new URL(Location));
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return url;
}

To get "User-Agent" and "Referer" by yourself, just go to developer mode of one of your installed browser (E.g. press F12 on Google Chrome). Then go to tab 'Network' and then click on one of the requests. You should see it's details. Just press 'Headers' sub tab (the image below) request details

Python None comparison: should I use "is" or ==?

Summary:

Use is when you want to check against an object's identity (e.g. checking to see if var is None). Use == when you want to check equality (e.g. Is var equal to 3?).

Explanation:

You can have custom classes where my_var == None will return True

e.g:

class Negator(object):
    def __eq__(self,other):
        return not other

thing = Negator()
print thing == None    #True
print thing is None    #False

is checks for object identity. There is only 1 object None, so when you do my_var is None, you're checking whether they actually are the same object (not just equivalent objects)

In other words, == is a check for equivalence (which is defined from object to object) whereas is checks for object identity:

lst = [1,2,3]
lst == lst[:]  # This is True since the lists are "equivalent"
lst is lst[:]  # This is False since they're actually different objects

Angular 6: saving data to local storage

First you should understand how localStorage works. you are doing wrong way to set/get values in local storage. Please read this for more information : How to Use Local Storage with JavaScript

How to turn off Wifi via ADB?

In Android tests I'm doing so: InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand("svc wifi enable") InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand("svc wifi disable")

Zooming MKMapView to fit annotation pins?

In Swift use

mapView.showAnnotations(annotationArray, animated: true)

In Objective c

[mapView showAnnotations:annotationArray animated:YES];

Return 0 if field is null in MySQL

None of the above answers were complete for me. If your field is named field, so the selector should be the following one:

IFNULL(`field`,0) AS field

For example in a SELECT query:

SELECT IFNULL(`field`,0) AS field, `otherfield` FROM `mytable`

Hope this can help someone to not waste time.

How to allow users to check for the latest app version from inside the app?

If it is an application on the Market, then on app start-up, fire an Intent to open up the Market app hopefully which will cause it to check for updates.

Otherwise implementing and update checker is fairly easy. Here is my code (roughly) for it:

String response = SendNetworkUpdateAppRequest(); // Your code to do the network request
                                                 // should send the current version
                                                 // to server
if(response.equals("YES")) // Start Intent to download the app user has to manually install it by clicking on the notification
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("URL TO LATEST APK")));

Of course you should rewrite this to do the request on a background thread but you get the idea.

If you like something a little but more complex but allows your app to automatically apply the update see here.

HTML iframe - disable scroll

This works for me:

<style>
*{overflow:hidden!important;}
html{overflow:scroll!important;}
</style>

Note: if you need scrollbar in any other element, also add css {overflow:scroll!important;} to that element

Find p-value (significance) in scikit-learn LinearRegression

This is kind of overkill but let's give it a go. First lets use statsmodel to find out what the p-values should be

import pandas as pd
import numpy as np
from sklearn import datasets, linear_model
from sklearn.linear_model import LinearRegression
import statsmodels.api as sm
from scipy import stats

diabetes = datasets.load_diabetes()
X = diabetes.data
y = diabetes.target

X2 = sm.add_constant(X)
est = sm.OLS(y, X2)
est2 = est.fit()
print(est2.summary())

and we get

                         OLS Regression Results                            
==============================================================================
Dep. Variable:                      y   R-squared:                       0.518
Model:                            OLS   Adj. R-squared:                  0.507
Method:                 Least Squares   F-statistic:                     46.27
Date:                Wed, 08 Mar 2017   Prob (F-statistic):           3.83e-62
Time:                        10:08:24   Log-Likelihood:                -2386.0
No. Observations:                 442   AIC:                             4794.
Df Residuals:                     431   BIC:                             4839.
Df Model:                          10                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const        152.1335      2.576     59.061      0.000     147.071     157.196
x1           -10.0122     59.749     -0.168      0.867    -127.448     107.424
x2          -239.8191     61.222     -3.917      0.000    -360.151    -119.488
x3           519.8398     66.534      7.813      0.000     389.069     650.610
x4           324.3904     65.422      4.958      0.000     195.805     452.976
x5          -792.1842    416.684     -1.901      0.058   -1611.169      26.801
x6           476.7458    339.035      1.406      0.160    -189.621    1143.113
x7           101.0446    212.533      0.475      0.635    -316.685     518.774
x8           177.0642    161.476      1.097      0.273    -140.313     494.442
x9           751.2793    171.902      4.370      0.000     413.409    1089.150
x10           67.6254     65.984      1.025      0.306     -62.065     197.316
==============================================================================
Omnibus:                        1.506   Durbin-Watson:                   2.029
Prob(Omnibus):                  0.471   Jarque-Bera (JB):                1.404
Skew:                           0.017   Prob(JB):                        0.496
Kurtosis:                       2.726   Cond. No.                         227.
==============================================================================

Ok, let's reproduce this. It is kind of overkill as we are almost reproducing a linear regression analysis using Matrix Algebra. But what the heck.

lm = LinearRegression()
lm.fit(X,y)
params = np.append(lm.intercept_,lm.coef_)
predictions = lm.predict(X)

newX = pd.DataFrame({"Constant":np.ones(len(X))}).join(pd.DataFrame(X))
MSE = (sum((y-predictions)**2))/(len(newX)-len(newX.columns))

# Note if you don't want to use a DataFrame replace the two lines above with
# newX = np.append(np.ones((len(X),1)), X, axis=1)
# MSE = (sum((y-predictions)**2))/(len(newX)-len(newX[0]))

var_b = MSE*(np.linalg.inv(np.dot(newX.T,newX)).diagonal())
sd_b = np.sqrt(var_b)
ts_b = params/ sd_b

p_values =[2*(1-stats.t.cdf(np.abs(i),(len(newX)-len(newX[0])))) for i in ts_b]

sd_b = np.round(sd_b,3)
ts_b = np.round(ts_b,3)
p_values = np.round(p_values,3)
params = np.round(params,4)

myDF3 = pd.DataFrame()
myDF3["Coefficients"],myDF3["Standard Errors"],myDF3["t values"],myDF3["Probabilities"] = [params,sd_b,ts_b,p_values]
print(myDF3)

And this gives us.

    Coefficients  Standard Errors  t values  Probabilities
0       152.1335            2.576    59.061         0.000
1       -10.0122           59.749    -0.168         0.867
2      -239.8191           61.222    -3.917         0.000
3       519.8398           66.534     7.813         0.000
4       324.3904           65.422     4.958         0.000
5      -792.1842          416.684    -1.901         0.058
6       476.7458          339.035     1.406         0.160
7       101.0446          212.533     0.475         0.635
8       177.0642          161.476     1.097         0.273
9       751.2793          171.902     4.370         0.000
10       67.6254           65.984     1.025         0.306

So we can reproduce the values from statsmodel.

How to delete specific characters from a string in Ruby?

Here is an even shorter way of achieving this:

1) using Negative character class pattern matching

irb(main)> "((String1))"[/[^()]+/]
=> "String1"

^ - Matches anything NOT in the character class. Inside the charachter class, we have ( and )

Or with global substitution "AKA: gsub" like others have mentioned.

irb(main)> "((String1))".gsub(/[)(]/, '')
=> "String1"

Input from the keyboard in command line application

import Foundation
print("Enter a number")
let number : Int = Int(readLine(strippingNewline: true)!) ?? 0
if(number < 5)
{
    print("Small")
}else{
    print("Big")
}
for i in 0...number{
    print(i)
}

Instant run in Android Studio 2.0 (how to turn off)

the design in android 2.3 (stable version) is slightly changed.

File ? Settings ? Build, Execution, Deployment ? Instant Run and uncheck Enable Instant Run.

enter image description here

How to convert currentTimeMillis to a date in Java?

If the millis value is number of millis since Jan 1, 1970 GMT, as is standard for the JVM, then that is independent of time zone. If you want to format it with a specific time zone, you can simply convert it to a GregorianCalendar object and set the timezone. After that there are numerous ways to format it.

Is there any way to specify a suggested filename when using data: URI?

Use the download attribute:

<a download='FileName' href='your_url'>

The download attribute works on Chrome, Firefox, Edge, Opera, desktop Safari 10+, iOS Safari 13+, and not IE11.

Are nested try/except blocks in Python a good programming practice?

In Python it is easier to ask for forgiveness than permission. Don't sweat the nested exception handling.

(Besides, has* almost always uses exceptions under the cover anyway.)

Push method in React Hooks (useState)?

// Save search term state to React Hooks with spread operator and wrapper function

// Using .concat(), no wrapper function (not recommended)
setSearches(searches.concat(query))

// Using .concat(), wrapper function (recommended)
setSearches(searches => searches.concat(query))

// Spread operator, no wrapper function (not recommended)
setSearches([...searches, query])

// Spread operator, wrapper function (recommended)
setSearches(searches => [...searches, query])

https://medium.com/javascript-in-plain-english/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc