Programs & Examples On #Dataimporthandler

The DataImportHandler is a Solr contrib that provides a configuration driven way to import data into Solr, supporting both full and incremental (delta) import.

A Simple, 2d cross-platform graphics library for c or c++?

What about SDL?

Perhaps it's a bit too complex for your needs, but it's certainly cross-platform.

Programmatically read from STDIN or input file in Perl

This provides a named variable to work with:

foreach my $line ( <STDIN> ) {
    chomp( $line );
    print "$line\n";
}

To read a file, pipe it in like this:

program.pl < inputfile

How to delete a whole folder and content?

Safest code I know:

private boolean recursiveRemove(File file) {
    if(file == null  || !file.exists()) {
        return false;
    }

    if(file.isDirectory()) {
        File[] list = file.listFiles();

        if(list != null) {

            for(File item : list) {
                recursiveRemove(item);
            }

        }
    }

    if(file.exists()) {
        file.delete();
    }

    return !file.exists();
}

Checks the file exists, handles nulls, checks the directory was actually deleted

fatal error: mpi.h: No such file or directory #include <mpi.h>

On my system, I was just missing the Linux package.

sudo apt install libopenmpi-dev
pip install mpi4py

(example of something that uses it that is a good instant test to see if it succeeded)

Succeded.

What is the maximum length of a URL in different browsers?

Why is the Internet Explorer limit only 2K while IIS has a limit of 16K? I don't think it makes sense.

So I want to start an experiment about Ajax request URL size limits.

I have set my Tomcat HTTP connector's maxHttpHeaderSize="1048576". And prepared a very long URL.

Then I send a request with the long URL like the following:

var url="/ajax/url-length.jsp";
jQuery.ajax(url,{data:{q:"0".repeat(1048000-url.length-4)}});

jQuery reports done. Tomcat reports the URL requested is 1048015 bytes. It was tested with Chrome 50 and Internet Explorer 11.

So web browsers won't truncate or limit your URL intentionally when sending Ajax requests.

Python strptime() and timezones?

The datetime module documentation says:

Return a datetime corresponding to date_string, parsed according to format. This is equivalent to datetime(*(time.strptime(date_string, format)[0:6])).

See that [0:6]? That gets you (year, month, day, hour, minute, second). Nothing else. No mention of timezones.

Interestingly, [Win XP SP2, Python 2.6, 2.7] passing your example to time.strptime doesn't work but if you strip off the " %Z" and the " EST" it does work. Also using "UTC" or "GMT" instead of "EST" works. "PST" and "MEZ" don't work. Puzzling.

It's worth noting this has been updated as of version 3.2 and the same documentation now also states the following:

When the %z directive is provided to the strptime() method, an aware datetime object will be produced. The tzinfo of the result will be set to a timezone instance.

Note that this doesn't work with %Z, so the case is important. See the following example:

In [1]: from datetime import datetime

In [2]: start_time = datetime.strptime('2018-04-18-17-04-30-AEST','%Y-%m-%d-%H-%M-%S-%Z')

In [3]: print("TZ NAME: {tz}".format(tz=start_time.tzname()))
TZ NAME: None

In [4]: start_time = datetime.strptime('2018-04-18-17-04-30-+1000','%Y-%m-%d-%H-%M-%S-%z')

In [5]: print("TZ NAME: {tz}".format(tz=start_time.tzname()))
TZ NAME: UTC+10:00

C++ - unable to start correctly (0xc0150002)

I met such problem. Visual Studio 2008 clearly said: problem was caused by libtiff.dll. It cannot be loaded for some reasom, caused by its manifest (as a matter of fact, this dll has no manifest at all). I fixed it, when I had removed libtiff.dll from my project (but simultaneously I lost ability to open compressed TIFFs!). I recompiled aforementioned dll, but problem still remains. Interesting, that at my own machine I have no such error. Three others comps refused to load my prog. Attention!!! Here http://www.error-repair-tools.com/ppc/error.php?t=0xc0150002 one wise boy wrote, that this error was caused by problem with registry and offers repair tool. I have a solid guess, that this "repair tool" will install some malicious soft at your comp.

RestTemplate: How to send URL and query parameters together

One-liner using TestRestTemplate.exchange function with parameters map.

restTemplate.exchange("/someUrl?id={id}", HttpMethod.GET, reqEntity, respType, ["id": id])

The params map initialized like this is a groovy initializer*

Barcode scanner for mobile phone for Website in form

Scandit is a startup whose goal is to replace bulky, expensive laser barcode scanners with cheap mobile phones.

There are SDKs for Android, iOS, Windows, C API/Linux, React Native, Cordova/PhoneGap, Xamarin.

There is also Scandit Barcode Scanner SDK for the Web which the WebAssembly version of the SDK. It runs in modern browsers, also on phones.

There's a client library that also provides a barcode picker component. It can be used like this:

<div id="barcode-picker" style="max-width: 1280px; max-height: 80%;"></div>

<script src="https://unpkg.com/scandit-sdk"></script>
<script>
    console.log('Loading...');
    ScanditSDK.configure("xxx", {
engineLocation: "https://unpkg.com/scandit-sdk/build/"
    }).then(() => {
      console.log('Loaded');
      ScanditSDK.BarcodePicker.create(document.getElementById('barcode-picker'), {
        playSoundOnScan: true,
        vibrateOnScan: true
      }).then(function(barcodePicker) {
        console.log("Ready");
        barcodePicker.applyScanSettings(new ScanditSDK.ScanSettings({
          enabledSymbologies: ["ean8", "ean13", "upca", "upce", "code128", "code39", "code93", "itf", "qr"],
          codeDuplicateFilter: 1000
        }));
        barcodePicker.onScan(function(barcodes) {
          console.log(barcodes);
        });
      });
    });
</script>

Disclaimer: I work for Scandit

React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

I suggest to look at Dan Abramov (one of the React core maintainers) answer here:

I think you're making it more complicated than it needs to be.

function Example() {
  const [data, dataSet] = useState<any>(null)

  useEffect(() => {
    async function fetchMyAPI() {
      let response = await fetch('api/data')
      response = await response.json()
      dataSet(response)
    }

    fetchMyAPI()
  }, [])

  return <div>{JSON.stringify(data)}</div>
}

Longer term we'll discourage this pattern because it encourages race conditions. Such as — anything could happen between your call starts and ends, and you could have gotten new props. Instead, we'll recommend Suspense for data fetching which will look more like

const response = MyAPIResource.read();

and no effects. But in the meantime you can move the async stuff to a separate function and call it.

You can read more about experimental suspense here.


If you want to use functions outside with eslint.

 function OutsideUsageExample() {
  const [data, dataSet] = useState<any>(null)

  const fetchMyAPI = useCallback(async () => {
    let response = await fetch('api/data')
    response = await response.json()
    dataSet(response)
  }, [])

  useEffect(() => {
    fetchMyAPI()
  }, [fetchMyAPI])

  return (
    <div>
      <div>data: {JSON.stringify(data)}</div>
      <div>
        <button onClick={fetchMyAPI}>manual fetch</button>
      </div>
    </div>
  )
}

If you will use useCallback, look at example of how it works useCallback. Sandbox.

import React, { useState, useEffect, useCallback } from "react";

export default function App() {
  const [counter, setCounter] = useState(1);

  // if counter is changed, than fn will be updated with new counter value
  const fn = useCallback(() => {
    setCounter(counter + 1);
  }, [counter]);

  // if counter is changed, than fn will not be updated and counter will be always 1 inside fn
  /*const fnBad = useCallback(() => {
      setCounter(counter + 1);
    }, []);*/

  // if fn or counter is changed, than useEffect will rerun
  useEffect(() => {
    if (!(counter % 2)) return; // this will stop the loop if counter is not even

    fn();
  }, [fn, counter]);

  // this will be infinite loop because fn is always changing with new counter value
  /*useEffect(() => {
    fn();
  }, [fn]);*/

  return (
    <div>
      <div>Counter is {counter}</div>
      <button onClick={fn}>add +1 count</button>
    </div>
  );
}

Appending a line to a file only if it does not already exist

Just keep it simple :)

grep + echo should suffice:

grep -qxF 'include "/configs/projectname.conf"' foo.bar || echo 'include "/configs/projectname.conf"' >> foo.bar

Edit: incorporated @cerin and @thijs-wouters suggestions.

Reading from a text file and storing in a String

These are the necersary imports:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

And this is a method that will allow you to read from a File by passing it the filename as a parameter like this: readFile("yourFile.txt");

String readFile(String fileName) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        return sb.toString();
    } finally {
        br.close();
    }
}

How to use Lambda in LINQ select statement

Why not just use all Lambda syntax?

database.Stores.Where(s => s.CompanyID == curCompany.ID)
               .Select(s => new SelectListItem
                   {
                       Value = s.Name,
                       Text = s.ID
                   });

Find if variable is divisible by 2

Use modulus:

// Will evaluate to true if the variable is divisible by 2
variable % 2 === 0  

Screen width in React Native

Only two simple steps.

  1. import { Dimensions } from 'react-native' at top of your file.
  2. const { height } = Dimensions.get('window');

now the window screen height is stored in the height variable.

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF

There is pre-mentioned OperationId in your query which should not be there as it is auto increamented

Insert table(OperationID,OpDescription,FilterID)
values (20,'Hierachy Update',1)

so your query will be

Insert table(OpDescription,FilterID)
values ('Hierachy Update',1)

New og:image size for Facebook share?

The aspect ratio for a Facebook post image is 41:20.

To find the appropriate widths and height for your photo, you can use the Aspect Ratio Calculator.

Here you can select different ratios under “Common ratios:” which includes the option “1200 x 630 (Facebook)". So if the width of your photo is 1800, plug that number into the “W2” slot and it will tell you what the respective height should be.

ios app maximum memory budget

- (float)__getMemoryUsedPer1
{
    struct mach_task_basic_info info;
    mach_msg_type_number_t size = MACH_TASK_BASIC_INFO;
    kern_return_t kerr = task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)&info, &size);
    if (kerr == KERN_SUCCESS)
    {
        float used_bytes = info.resident_size;
        float total_bytes = [NSProcessInfo processInfo].physicalMemory;
        //NSLog(@"Used: %f MB out of %f MB (%f%%)", used_bytes / 1024.0f / 1024.0f, total_bytes / 1024.0f / 1024.0f, used_bytes * 100.0f / total_bytes);
        return used_bytes / total_bytes;
    }
    return 1;
}

If one will use TASK_BASIC_INFO_COUNT instead of MACH_TASK_BASIC_INFO, you will get

kerr == KERN_INVALID_ARGUMENT (4)

Check if a Windows service exists and delete in PowerShell

If you just want to check service existence:

if (Get-Service "My Service" -ErrorAction SilentlyContinue)
{
    "service exists"
}

Can I use a min-height for table, tr or td?

In CSS 2.1, the effect of 'min-height' and 'max-height' on tables, inline tables, table cells, table rows, and row groups is undefined.

So try wrapping the content in a div, and give the div a min-height jsFiddle here

<table cellspacing="0" cellpadding="0" border="0" style="width:300px">
    <tbody>
        <tr>
            <td>
                <div style="min-height: 100px; background-color: #ccc">
                    Hello World !
                </div>
            </td>
            <td>
                <div style="min-height: 100px; background-color: #f00">
                    Good Morning !
                </div>
            </td>
        </tr>
    </tbody>
</table>

rewrite a folder name using .htaccess

mod_rewrite can only rewrite/redirect requested URIs. So you would need to request /apple/… to get it rewritten to a corresponding /folder1/….

Try this:

RewriteEngine on
RewriteRule ^apple/(.*) folder1/$1

This rule will rewrite every request that starts with the URI path /apple/… internally to /folder1/….


Edit    As you are actually looking for the other way round:

RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /apple/$1 [L,R=301]

This rule is designed to work together with the other rule above. Requests of /folder1/… will be redirected externally to /apple/… and requests of /apple/… will then be rewritten internally back to /folder1/….

How to get Linux console window width in Python

I was trying the solution from here that calls out to stty size:

columns = int(subprocess.check_output(['stty', 'size']).split()[1])

However this failed for me because I was working on a script that expects redirected input on stdin, and stty would complain that "stdin isn't a terminal" in that case.

I was able to make it work like this:

with open('/dev/tty') as tty:
    height, width = subprocess.check_output(['stty', 'size'], stdin=tty).split()

C# error: "An object reference is required for the non-static field, method, or property"

The Main method is static inside the Program class. You can't call an instance method from inside a static method, which is why you're getting the error.

To fix it you just need to make your GetRandomBits() method static as well.

Using bind variables with dynamic SELECT INTO clause in PL/SQL

In my opinion, a dynamic PL/SQL block is somewhat obscure. While is very flexible, is also hard to tune, hard to debug and hard to figure out what's up. My vote goes to your first option,

EXECUTE IMMEDIATE v_query_str INTO v_num_of_employees USING p_job;

Both uses bind variables, but first, for me, is more redeable and tuneable than @jonearles option.

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

With C#6.0 you also have a new way of formatting date when using string interpolation e.g.

$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"

Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.

More about string interpolation.

Is it possible to decompile a compiled .pyc file into a .py file?

Yes, it is possible.

There is a perfect open-source Python (.PYC) decompiler, called Decompyle++ https://github.com/zrax/pycdc/

Decompyle++ aims to translate compiled Python byte-code back into valid and human-readable Python source code. While other projects have achieved this with varied success, Decompyle++ is unique in that it seeks to support byte-code from any version of Python.

Hide/Show Column in an HTML Table

The following is building on Eran's code, with a few minor changes. Tested it and it seems to work fine on Firefox 3, IE7.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<script>
$(document).ready(function() {
    $('input[type="checkbox"]').click(function() {
        var index = $(this).attr('name').substr(3);
        index--;
        $('table tr').each(function() { 
            $('td:eq(' + index + ')',this).toggle();
        });
        $('th.' + $(this).attr('name')).toggle();
    });
});
</script>
<body>
<table>
<thead>
    <tr>
        <th class="col1">Header 1</th>
        <th class="col2">Header 2</th>
        <th class="col3">Header 3</th>
    </tr>
</thead>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
</table>

<form>
    <input type="checkbox" name="col1" checked="checked" /> Hide/Show Column 1 <br />
    <input type="checkbox" name="col2" checked="checked" /> Hide/Show Column 2 <br />
    <input type="checkbox" name="col3" checked="checked" /> Hide/Show Column 3 <br />
</form>
</body>
</html>

Converting std::__cxx11::string to std::string

Is it possible that you are using GCC 5?

If you get linker errors about undefined references to symbols that involve types in the std::__cxx11 namespace or the tag [abi:cxx11] then it probably indicates that you are trying to link together object files that were compiled with different values for the _GLIBCXX_USE_CXX11_ABI macro. This commonly happens when linking to a third-party library that was compiled with an older version of GCC. If the third-party library cannot be rebuilt with the new ABI then you will need to recompile your code with the old ABI.

Source: GCC 5 Release Notes/Dual ABI

Defining the following macro before including any standard library headers should fix your problem: #define _GLIBCXX_USE_CXX11_ABI 0

How do I remove whitespace from the end of a string in Python?

You can use strip() or split() to control the spaces values as in the following:

words = "   first  second   "

# Remove end spaces
def remove_end_spaces(string):
    return "".join(string.rstrip())


# Remove the first and end spaces
def remove_first_end_spaces(string):
    return "".join(string.rstrip().lstrip())


# Remove all spaces
def remove_all_spaces(string):
    return "".join(string.split())


# Show results
print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))

Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

This can happen if you accidentally are not dragging the element that does have an id assigned (for example you are dragging the surrounding element). In that case the ID is empty and the function drag() is assigning an empty value which is then passed to drop() and fails there.

Try assigning the ids to all of your elements, including the tds, divs, or whatever is around your draggable element.

How to create the pom.xml for a Java project with Eclipse

To create pom.xml file follow the next steps:

  1. Right click on the current project
  2. Select Configure option
  3. Select Convert to Maven Project
  4. Complete all fields in Create new POM window
  5. Check "Delete original references from project"
  6. Click on Finish button

If eclipse show the the error "Maven error “Failure to transfer…", follow the next steps

  1. Copy the dependency to pom.

    <dependency>
        <groupId>org.apache.maven</groupId>
        <artifactId>maven-archiver</artifactId>
        <version>2.5</version>
    </dependency>
    
  2. Click right on your project

  3. Select Maven
  4. Select Update project
  5. Select Force Update of Snapshots/Releases

how to get the last character of a string?

You can get the last char like this :

var lastChar=yourString.charAt(yourString.length-1);

JS: iterating over result of getElementsByClassName using Array.forEach

You can use Array.from to convert collection to array, which is way cleaner than Array.prototype.forEach.call:

Array.from(document.getElementsByClassName("myclass")).forEach(
    function(element, index, array) {
        // do stuff
    }
);

In older browsers which don't support Array.from, you need to use something like Babel.


ES6 also adds this syntax:

[...document.getElementsByClassName("myclass")].forEach(
    (element, index, array) => {
        // do stuff
    }
);

Rest destructuring with ... works on all array-like objects, not only arrays themselves, then good old array syntax is used to construct an array from the values.


While the alternative function querySelectorAll (which kinda makes getElementsByClassName obsolete) returns a collection which does have forEach natively, other methods like map or filter are missing, so this syntax is still useful:

[...document.querySelectorAll(".myclass")].map(
    (element, index, array) => {
        // do stuff
    }
);

[...document.querySelectorAll(".myclass")].map(element => element.innerHTML);

How to debug Angular JavaScript Code

Since the add-ons don't work anymore, the most helpful set of tools I've found is using Visual Studio/IE because you can set breakpoints in your JS and inspect your data that way. Of course Chrome and Firefox have much better dev tools in general. Also, good ol' console.log() has been super helpful!

New line in JavaScript alert box

You can use \n for new line

alert("Welcome\nto Jumanji");

_x000D_
_x000D_
alert("Welcome\nto Jumanji");
_x000D_
_x000D_
_x000D_

How to access a dictionary key value present inside a list?

If you know which dict in the list has the key you're looking for, then you already have the solution (as presented by Matt and Ignacio). However, if you don't know which dict has this key, then you could do this:

def getValueOf(k, L):
    for d in L:
        if k in d:
            return d[k]

Pass Javascript variable to PHP via ajax

$(document).ready(function() {
            $(".clickable").click(function() {
                var userID = $(this).attr('id'); // you can add here your personal ID
                //alert($(this).attr('id'));
                $.ajax({
                    type: "POST",
                    url: 'logtime.php',
                    data : {
                        action : 'my_action',
                        userID : userID 
                    },
                    success: function(data)
                    {
                        alert("success!");
                        console.log(data);
                    }
                });
            });
        });


 $uid = (isset($_POST['userID'])) ? $_POST['userID'] : 'ID not found';
 echo $uid;

$uid add in your functions

note: if $ is not supperted than add jQuery where $ defined

AutoComplete TextBox Control

private void textBox1_TextChanged(object sender, EventArgs e)
    {
        try
        {
            textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
            textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
            AutoCompleteStringCollection col = new AutoCompleteStringCollection();
            con.Open();
            sql = "select *from Table_Name;
            cmd = new SqlCommand(sql, con);
            SqlDataReader sdr = null;
            sdr = cmd.ExecuteReader();
            while (sdr.Read())
            {
                col.Add(sdr["Column_Name"].ToString());
            }
            sdr.Close(); 

            textBox1.AutoCompleteCustomSource = col;
            con.Close();
        }
        catch
        {
        }
    }

Why does JSHint throw a warning if I am using const?

In your package.json you can tell Jshint to use es6 like this

"jshintConfig":{
    "esversion": 6 
}

Passing multiple values for a single parameter in Reporting Services

Although John Sansom's solution works, there's another way to do this, without having to use a potentially inefficient scalar valued UDF. In the SSRS report, on the parameters tab of the query definition, set the parameter value to

=join(Parameters!<your param name>.Value,",")

In your query, you can then reference the value like so:

where yourColumn in (@<your param name>)

Bring element to front using CSS

Add z-index:-1 and position:relative to .content

_x000D_
_x000D_
#header {_x000D_
    background: url(http://placehold.it/420x160) center top no-repeat;_x000D_
}_x000D_
#header-inner {_x000D_
    background: url(http://placekitten.com/150/200) right top no-repeat;_x000D_
}_x000D_
.logo-class {_x000D_
    height: 128px;_x000D_
}_x000D_
.content {_x000D_
    margin-left: auto;_x000D_
    margin-right: auto;_x000D_
    table-layout: fixed;_x000D_
    border-collapse: collapse;_x000D_
    z-index: -1;_x000D_
    position:relative;_x000D_
}_x000D_
.td-main {_x000D_
    text-align: center;_x000D_
    padding: 80px 10px 80px 10px;_x000D_
    border: 1px solid #A02422;_x000D_
    background: #ABABAB;_x000D_
}
_x000D_
<body>_x000D_
    <div id="header">_x000D_
        <div id="header-inner">_x000D_
            <table class="content">_x000D_
                <col width="400px" />_x000D_
                <tr>_x000D_
                    <td>_x000D_
                        <table class="content">_x000D_
                            <col width="400px" />_x000D_
                            <tr>_x000D_
                                <td>_x000D_
                                    <div class="logo-class"></div>_x000D_
                                </td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td id="menu"></td>_x000D_
                            </tr>_x000D_
                        </table>_x000D_
                        <table class="content">_x000D_
                            <col width="120px" />_x000D_
                            <col width="160px" />_x000D_
                            <col width="120px" />_x000D_
                            <tr>_x000D_
                                <td class="td-main">text</td>_x000D_
                                <td class="td-main">text</td>_x000D_
                                <td class="td-main">text</td>_x000D_
                            </tr>_x000D_
                        </table>_x000D_
                    </td>_x000D_
                </tr>_x000D_
            </table>_x000D_
        </div>_x000D_
        <!-- header-inner -->_x000D_
    </div>_x000D_
    <!-- header -->_x000D_
</body>
_x000D_
_x000D_
_x000D_

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

If you don't need to handle raster files and PDF/PS/EPS through the same tool, don't loosen ImageMagick's security.

Instead, keep your defense in depth for your web applications intact, check that your Ghostscript has been patched for all known -dSAFER vulnerabilities and then invoke it directly.

gs -dSAFER -r300 -sDEVICE=png16m -o document-%03d.png document.pdf
  • -dSAFER opts you out of the legacy-compatibility "run Postscript will full permission to interact with the outside world as a turing-complete programming language" mode.
  • -r300 sets the desired DPI to 300 (the default is 72)
  • -sDEVICE specifies the output format (See the Devices section of the manual for other choices.)
  • -o is a shorthand for -dBATCH -dNOPAUSE -sOutputFile=
  • This section of the Ghostscript manual gives some example formats for for multi-file filename output but, for the actual syntax definition, it points you at the documentation for the C printf(3) function.

If you're rendering EPS files, add -dEPSCrop so it won't pad your output to page size and use -sDEVICE=pngalpha to get transparent backgrounds.

Initialising a multidimensional array in Java

Java doesn't have "true" multidimensional arrays.

For example, arr[i][j][k] is equivalent to ((arr[i])[j])[k]. In other words, arr is simply an array, of arrays, of arrays.

So, if you know how arrays work, you know how multidimensional arrays work!


Declaration:

int[][][] threeDimArr = new int[4][5][6];

or, with initialization:

int[][][] threeDimArr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };

Access:

int x = threeDimArr[1][0][1];

or

int[][] row = threeDimArr[1];

String representation:

Arrays.deepToString(threeDimArr);

yields

"[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]"

Useful articles

How can I get a list of repositories 'apt-get' is checking?

It's not a format suitable for blindly copying to another machine, but users who wish to work out whether they've added a repository yet or not (like I did), you can just do:

sudo apt update

When apt is updating, it outputs a list of repositories it fetches. It seems obvious, but I've just realised what the GET URLs are that it spits out.

The following awk-based expression could be used to generate a sources.list file:

 cat /tmp/apt-update.txt | awk '/http/ { gsub("/", " ", $3); gsub("^\s\*$", "main", $3); printf("deb "); if($4 ~ "^[a-z0-9]$") printf("[arch=" $4 "] "); print($2 " " $3) }' | sort | uniq

Alternatively, as other answers suggest, you could just cat all the pre-existing sources like this:

cat /etc/apt/sources.list /etc/apt/sources.list.d/*

Since the disabled repositories are commented out with hash, this should work as intended.

How to replace string in Groovy

You need to escape the backslash \:

println yourString.replace("\\", "/")

Putting an if-elif-else statement on one line?

People have already mentioned ternary expressions. Sometimes with a simple conditional assignment as your example, it is possible to use a mathematical expression to perform the conditional assignment. This may not make your code very readable, but it does get it on one fairly short line. Your example could be written like this:

x = 2*(i>100) | 1*(i<100)

The comparisons would be True or False, and when multiplying with numbers would then be either 1 or 0. One could use a + instead of an | in the middle.

How to validate email id in angularJs using ng-pattern

Now, Angular 4 has email validator built-in https://github.com/angular/angular/blob/master/CHANGELOG.md#features-6 https://github.com/angular/angular/pull/13709

Just add email to the tag. For example

  <form #f="ngForm">
    <input type="email" ngModel name="email" required email>
    <button [disabled]="!f.valid">Submit</button>
    <p>Form State: {{f.valid?'VALID':'INVALID'}}</p>
  </form>

Anaconda Navigator won't launch (windows 10)

I had the same issue, and solved it by the following commands:

conda update conda
conda update anaconda-navigator
anaconda-navigator --reset
anaconda-navigator

How to get current time in milliseconds in PHP?

Use microtime. This function returns a string separated by a space. The first part is the fractional part of seconds, the second part is the integral part. Pass in true to get as a number:

var_dump(microtime());       // string(21) "0.89115400 1283846202"
var_dump(microtime(true));   // float(1283846202.89)

Beware of precision loss if you use microtime(true).

There is also gettimeofday that returns the microseconds part as an integer.

var_dump(gettimeofday());
/*
array(4) {
  ["sec"]=>
  int(1283846202)
  ["usec"]=>
  int(891199)
  ["minuteswest"]=>
  int(-60)
  ["dsttime"]=>
  int(1)
}
*/

How to downgrade from Internet Explorer 11 to Internet Explorer 10?

  1. Save and close all Internet Explorer windows and then, run Windows Task Manager to end the running processes in background.
  2. Go to Control Panel.
  3. Click Programs and choose the View installed updates instead.
  4. Locate the following Windows Internet Explorer 11 or you can type "Internet Explorer" for a quick search.
  5. Choose the Yes option from the following "Uninstall an update".
  6. Please wait while Windows Internet Explorer 10 is being restored and reconfigured automatically.
  7. Follow the Microsoft Windows wizard to restart your system.

Note: You can do it for as many earlier versions you want, i.e. IE9, IE8 and so on.

javascript - pass selected value from popup window to parent window input box

My approach: use a div instead of a pop-up window.

See it working in the jsfiddle here: http://jsfiddle.net/6RE7w/2/

Or save the code below as test.html and try it locally.

<html>

<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script type="text/javascript">
        $(window).load(function(){
            $('.btnChoice').on('click', function(){
                $('#divChoices').show()
                thefield = $(this).prev()
                $('.btnselect').on('click', function(){
                    theselected = $(this).prev()
                    thefield.val( theselected.val() )
                    $('#divChoices').hide()
                })
            })

            $('#divChoices').css({
                'border':'2px solid red',
                'position':'fixed',
                'top':'100',
                'left':'200',
                'display':'none'
            })
        });
    </script>
</head>

<body>

<div class="divform">
    <input type="checkbox" name="kvi1" id="kvi1" value="1">
    <label>Field 1: </label>
    <input size="10" type="number" id="sku1" name="sku1">
    <button id="choice1" class="btnChoice">?</button>
    <br>
    <input type="checkbox" name="kvi2" id="kvi2" value="2">
    <label>Field 2: </label>
    <input size="10"  type="number" id="sku2" name="sku2">
    <button id="choice2" class="btnChoice">?</button>
</div>

<div id="divChoices">
    Select something: 
    <br>
    <input size="10" type="number" id="ch1" name="ch1" value="11">
    <button id="btnsel1" class="btnselect">Select</button>
    <label for="ch1">bla bla bla</label>
    <br>
    <input size="10" type="number" id="ch2" name="ch2" value="22">
    <button id="btnsel2" class="btnselect">Select</button>
    <label for="ch2">ble ble ble</label>
</div>

</body>

</html>

clean and simple.

fcntl substitute on Windows

Although this does not help you right away, there is an alternative that can work with both Unix (fcntl) and Windows (win32 api calls), called: portalocker

It describes itself as a cross-platform (posix/nt) API for flock-style file locking for Python. It basically maps fcntl to win32 api calls.

The original code at http://code.activestate.com/recipes/65203/ can now be installed as a separate package - https://pypi.python.org/pypi/portalocker

Javascript array value is undefined ... how do I test for that

predQuery[preId]=='undefined'

You're testing against the string 'undefined'; you've confused this test with the typeof test which would return a string. You probably mean to be testing against the special value undefined:

predQuery[preId]===undefined

Note the strict-equality operator to avoid the generally-unwanted match null==undefined.

However there are two ways you can get an undefined value: either preId isn't a member of predQuery, or it is a member but has a value set to the special undefined value. Often, you only want to check whether it's present or not; in that case the in operator is more appropriate:

!(preId in predQuery)

initialize a vector to zeros C++/C++11

You don't need initialization lists for that:

std::vector<int> vector1(length, 0);
std::vector<double> vector2(length, 0.0);

MySQL Data Source not appearing in Visual Studio

Tried everything but on Visual Studio 2015 Community edition I got it working when I installed MySQL for Visual Studio 1.2.4+ from http://dev.mysql.com/downloads/windows/visualstudio/ At time of writing I could download 1.2.6 which worked for me.

enter image description here

Release notes of 1.2.4 which adds support for VS2015 can be found at http://forums.mysql.com/read.php?3,633391

Testing if a list of integer is odd or even

        #region even and odd numbers
        for (int x = 0; x <= 50; x = x + 2)
        {

            int y = 1;
            y = y + x;
            if (y < 50)
            {
                Console.WriteLine("Odd number is #{" + x + "} : even number is #{" + y + "} order by Asc");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("Odd number is #{" + x + "} : even number is #{0} order by Asc");
                Console.ReadKey();
            }

        }

        //order by desc

        for (int z = 50; z >= 0; z = z - 2)
        {
            int w = z;
            w = w - 1;
            if (w > 0)
            {
                Console.WriteLine("odd number is {" + z + "} : even number is {" + w + "} order by desc");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("odd number is {" + z + "} : even number is {0} order by desc");
                Console.ReadKey();
            }
        }

Prevent cell numbers from incrementing in a formula in Excel

Highlight "B1" and press F4. This will lock the cell.

Now you can drag it around and it will not change. The principle is simple. It adds a dollar sign before both coordinates. A dollar sign in front of a coordinate will lock it when you copy the formula around. You can have partially locked coordinates and fully locked coordinates.

How do I merge changes to a single file, rather than merging commits?

Assuming B is the current branch:

$ git diff A <file-path> > patch.tmp
$ git apply patch.tmp -R

Note that this only applies changes to the local file. You'll need to commit afterwards.

jQuery - Illegal invocation

My problem was unrelated to processData. It was because I sent a function that cannot be called later with apply because it did not have enough arguments. Specifically I shouldn't have used alert as the error callback.

$.ajax({
    url: csvApi,
    success: parseCsvs,
    dataType: "json",
    timeout: 5000,
    processData: false,
    error: alert
});

See this answer for more information on why that can be a problem: Why are certain function calls termed "illegal invocations" in JavaScript?

The way I was able to discover this was by adding a console.log(list[ firingIndex ]) to jQuery so I could track what it was firing.

This was the fix:

function myError(jqx, textStatus, errStr) {
    alert(errStr);
}

$.ajax({
    url: csvApi,
    success: parseCsvs,
    dataType: "json",
    timeout: 5000,
    error: myError // Note that passing `alert` instead can cause a "jquery.js:3189 Uncaught TypeError: Illegal invocation" sometimes
});

Assembly Language - How to do Modulo?

If you don't care too much about performance and want to use the straightforward way, you can use either DIV or IDIV.

DIV or IDIV takes only one operand where it divides a certain register with this operand, the operand can be register or memory location only.

When operand is a byte: AL = AL / operand, AH = remainder (modulus).

Ex:

MOV AL,31h ; Al = 31h

DIV BL ; Al (quotient)= 08h, Ah(remainder)= 01h

when operand is a word: AX = (AX) / operand, DX = remainder (modulus).

Ex:

MOV AX,9031h ; Ax = 9031h

DIV BX ; Ax=1808h & Dx(remainder)= 01h

How to find files modified in last x minutes (find -mmin does not work as expected)

This may work for you. I used it for cleaning folders during deployments for deleting old deployment files.

clean_anyfolder() {
    local temp2="$1/**"; //PATH
    temp3=( $(ls -d $temp2 -t | grep "`date | awk '{print $2" "$3}'`") )
    j=0;
    while [ $j -lt ${#temp3[@]} ]
    do
            echo "to be removed ${temp3[$j]}"
            delete_file_or_folder ${temp3[$j]} 0 //DELETE HERE
        fi
        j=`expr $j + 1`
    done
}

How to make JavaScript execute after page load?

I find sometimes on more complex pages that not all the elements have loaded by the time window.onload is fired. If that's the case, add setTimeout before your function to delay is a moment. It's not elegant but it's a simple hack that renders well.

window.onload = function(){ doSomethingCool(); };

becomes...

window.onload = function(){ setTimeout( function(){ doSomethingCool(); }, 1000); };

Displaying output of a remote command with Ansible

I'm not sure about the syntax of your specific commands (e.g., vagrant, etc), but in general...

Just register Ansible's (not-normally-shown) JSON output to a variable, then display each variable's stdout_lines attribute:

- name: Generate SSH keys for vagrant user
  user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048
  register: vagrant
- debug: var=vagrant.stdout_lines

- name: Show SSH public key
  command: /bin/cat $home_directory/.ssh/id_rsa.pub
  register: cat
- debug: var=cat.stdout_lines

- name: Wait for user to copy SSH public key
  pause: prompt="Please add the SSH public key above to your GitHub account"
  register: pause
- debug: var=pause.stdout_lines

jQuery preventDefault() not triggered

Try this:

$("div.subtab_left li.notebook a").click(function(e) {
    e.preventDefault();
});

Where IN clause in LINQ

This will translate to a where in clause in Linq to SQL...

var myInClause = new string[] {"One", "Two", "Three"};

var results = from x in MyTable
              where myInClause.Contains(x.SomeColumn)
              select x;
// OR
var results = MyTable.Where(x => myInClause.Contains(x.SomeColumn));

In the case of your query, you could do something like this...

var results = from states in _objectdatasource.StateList()
              where listofcountrycodes.Contains(states.CountryCode)
              select new State
              {
                  StateName = states.StateName
              };
// OR
var results = _objectdatasource.StateList()
                  .Where(s => listofcountrycodes.Contains(s.CountryCode))
                  .Select(s => new State { StateName = s.StateName});

WARNING in budgets, maximum exceeded for initial

Open angular.json file and find budgets keyword.

It should look like:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "2mb",
          "maximumError": "5mb"
       }
    ]

As you’ve probably guessed you can increase the maximumWarning value to prevent this warning, i.e.:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "4mb", <===
          "maximumError": "5mb"
       }
    ]

What does budgets mean?

A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.

In our case budget is the limit for bundle sizes.

See also:

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

Try this !!!. This will solve your problem for sure!

Method 1 -

Step 1 - Go to 'Environmental Variables'.

Step 2 - Find PATH variable and add the path to your PHP folder.

Step 3 - For 'XAMPP' users put 'C:\xampp\php' and 'WAMP' users put 'C:\wamp64\bin\php\php7.1.9' ) and save.

Method 2-

In VS Code

File -> Preferences -> Settings.

enter image description here

Open 'settings.json' file and put the below codes.

If you are using WAMP put this code and Save.

  "php.validate.executablePath": "C:\\wamp64\\bin\\php\\php7.1.9\\php.exe",
  "php.executablePath": "C:\\wamp64\\bin\\php\\php7.1.9\\php.exe"

If you are using XAMPP put this code and Save.

  "php.validate.executablePath": "C:\\xampp\\php\\php.exe",
  "php.executablePath": "C:\\xampp\\php\\php.exe"

Note - Replace php7.1.9 with your PHP version.

How to get the current time in milliseconds from C in Linux?

Use gettimeofday() to get the time in seconds and microseconds. Combining and rounding to milliseconds is left as an exercise.

A valid provisioning profile for this executable was not found... (again)

After wasting my half day I got this working.

Select Target > Edit Scheme > Select Run > Change Build Configuration to debug

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

Just to add to the other options, I was trying to access a nested object within the main object through the dot method as in: this.state.arrayData.CompleteAdress.Location In this case Location is a nested object inside Complete address which is why i cant simply access it with the dot notation.

  • So if you're facing this same issue, try JSON.parse so that you access the nested object and then manipulate accordingly.

What is Hash and Range Primary Key?

"Hash and Range Primary Key" means that a single row in DynamoDB has a unique primary key made up of both the hash and the range key. For example with a hash key of X and range key of Y, your primary key is effectively XY. You can also have multiple range keys for the same hash key but the combination must be unique, like XZ and XA. Let's use their examples for each type of table:

Hash Primary Key – The primary key is made of one attribute, a hash attribute. For example, a ProductCatalog table can have ProductID as its primary key. DynamoDB builds an unordered hash index on this primary key attribute.

This means that every row is keyed off of this value. Every row in DynamoDB will have a required, unique value for this attribute. Unordered hash index means what is says - the data is not ordered and you are not given any guarantees into how the data is stored. You won't be able to make queries on an unordered index such as Get me all rows that have a ProductID greater than X. You write and fetch items based on the hash key. For example, Get me the row from that table that has ProductID X. You are making a query against an unordered index so your gets against it are basically key-value lookups, are very fast, and use very little throughput.


Hash and Range Primary Key – The primary key is made of two attributes. The first attribute is the hash attribute and the second attribute is the range attribute. For example, the forum Thread table can have ForumName and Subject as its primary key, where ForumName is the hash attribute and Subject is the range attribute. DynamoDB builds an unordered hash index on the hash attribute and a sorted range index on the range attribute.

This means that every row's primary key is the combination of the hash and range key. You can make direct gets on single rows if you have both the hash and range key, or you can make a query against the sorted range index. For example, get Get me all rows from the table with Hash key X that have range keys greater than Y, or other queries to that affect. They have better performance and less capacity usage compared to Scans and Queries against fields that are not indexed. From their documentation:

Query results are always sorted by the range key. If the data type of the range key is Number, the results are returned in numeric order; otherwise, the results are returned in order of ASCII character code values. By default, the sort order is ascending. To reverse the order, set the ScanIndexForward parameter to false

I probably missed some things as I typed this out and I only scratched the surface. There are a lot more aspects to take into consideration when working with DynamoDB tables (throughput, consistency, capacity, other indices, key distribution, etc.). You should take a look at the sample tables and data page for examples.

What is the best data type to use for money in C#?

Create your own class. This seems odd, but a .Net type is inadequate to cover different currencies.

Get git branch name in Jenkins Pipeline/Jenkinsfile

Use multibranch pipeline job type, not the plain pipeline job type. The multibranch pipeline jobs do posess the environment variable env.BRANCH_NAME which describes the branch.

In my script..

stage('Build') {
    node {
        echo 'Pulling...' + env.BRANCH_NAME
        checkout scm
        
    }
}

Yields...

Pulling...master

How to get child element by ID in JavaScript?

Using jQuery

$('#note textarea');

or just

$('#textid');

Escaping ampersand character in SQL string

REPLACE(<your xml column>,'&',chr(38)||'amp;')

Using Mockito's generic "any()" method

Since Java 8 you can use the argument-less any method and the type argument will get inferred by the compiler:

verify(bar).doStuff(any());

Explanation

The new thing in Java 8 is that the target type of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only arguments to methods where used for type parameter inference (most of the time).

In this case the parameter type of doStuff will be the target type for any(), and the return value type of any() will get chosen to match that argument type.

This mechanism was added in Java 8 mainly to be able to compile lambda expressions, but it improves type inferences generally.


Primitive types

This doesn't work with primitive types, unfortunately:

public interface IBar {
    void doPrimitiveStuff(int i);
}

verify(bar).doPrimitiveStuff(any()); // Compiles but throws NullPointerException
verify(bar).doPrimitiveStuff(anyInt()); // This is what you have to do instead

The problem is that the compiler will infer Integer as the return value type of any(). Mockito will not be aware of this (due to type erasure) and return the default value for reference types, which is null. The runtime will try to unbox the return value by calling the intValue method on it before passing it to doStuff, and the exception gets thrown.

JavaFX "Location is required." even though it is in the same package

URL url = new File("src/main/java/ua/adeptius/goit/sample.fxml").toURI().toURL();
Parent root = FXMLLoader.load(url);

That is helped for me because

getClass.getResource("path")

always returns me null;

Unsafe JavaScript attempt to access frame with URL

From a child document of different origin you are not allowed access to the top window's location.hash property, but you are allowed to set the location property itself.

This means that given that the top windows location is http://example.com/page/, instead of doing

parent.location.hash = "#foobar";

you do need to know the parents location and do

parent.location = "http://example.com/page/#foobar";

Since the resource is not navigated this will work as expected, only changing the hash part of the url.

If you are using this for cross-domain communication, then I would recommend using easyXDM instead.

How to Select Top 100 rows in Oracle?

To select top n rows updated recently

SELECT * 
FROM (
   SELECT * 
   FROM table 
   ORDER BY UpdateDateTime DESC
)
WHERE ROWNUM < 101;

How to check if all inputs are not empty with jQuery

Use each:

var isValid;
$("input").each(function() {
   var element = $(this);
   if (element.val() == "") {
       isValid = false;
   }
});

However you probably will be better off using something like jQuery validate which IMO is cleaner.

JavaScript validation for empty input field

_x000D_
_x000D_
<script type="text/javascript">_x000D_
  function validateForm() {_x000D_
    var a = document.forms["Form"]["answer_a"].value;_x000D_
    var b = document.forms["Form"]["answer_b"].value;_x000D_
    var c = document.forms["Form"]["answer_c"].value;_x000D_
    var d = document.forms["Form"]["answer_d"].value;_x000D_
    if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {_x000D_
      alert("Please Fill All Required Field");_x000D_
      return false;_x000D_
    }_x000D_
  }_x000D_
</script>_x000D_
_x000D_
<form method="post" name="Form" onsubmit="return validateForm()" action="">_x000D_
  <textarea cols="30" rows="2" name="answer_a" id="a"></textarea>_x000D_
  <textarea cols="30" rows="2" name="answer_b" id="b"></textarea>_x000D_
  <textarea cols="30" rows="2" name="answer_c" id="c"></textarea>_x000D_
  <textarea cols="30" rows="2" name="answer_d" id="d"></textarea>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How can I print using JQuery

Try like

$('.printMe').click(function(){
     window.print();
});

or if you want to print selected area try like

$('.printMe').click(function(){
     $("#outprint").print();
});

Auto code completion on Eclipse

Its simple these are the steps: 1. first go to the following settings Window -> Preferences -> Java -> Editor -> content assist -> advanced 2. there will be two boxes having checkboxes. 3. check everthing in there and click apply. 4. now ofcourse when you'll be coding there will be auto code completion feature automatically.

Can't import Numpy in Python

Disabling pyright worked perfectly for me on VS.

Adding Apostrophe in every field in particular column for excel

More universal can be: for each v Selection : v.value = "'" & v.value : next and selecting range of cells before execution

Design Android EditText to show error message as described by google

reVerse's answer is great but it didn't point out how to remove the floating error tooltip kind of thing

You'll need edittext.setError(null) to remove that.
Also, as someone pointed out, you don't need TextInputLayout.setErrorEnabled(true)

Layout

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter something" />
</android.support.design.widget.TextInputLayout>

Code

TextInputLayout til = (TextInputLayout) editText.getParent();
til.setError("Your input is not valid...");
editText.setError(null);

Make UINavigationBar transparent

After doing what everyone else said above, i.e.:

navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController!.navigationBar.isTranslucent = true

... my navigation bar was still white. So I added this line:

navigationController?.navigationBar.backgroundColor = .clear

... et voila! That seemed to do the trick.

Colouring plot by factor in R

The command palette tells you the colours and their order when col = somefactor. It can also be used to set the colours as well.

palette()
[1] "black"   "red"     "green3"  "blue"    "cyan"    "magenta" "yellow"  "gray"   

In order to see that in your graph you could use a legend.

legend('topright', legend = levels(iris$Species), col = 1:3, cex = 0.8, pch = 1)

You'll notice that I only specified the new colours with 3 numbers. This will work like using a factor. I could have used the factor originally used to colour the points as well. This would make everything logically flow together... but I just wanted to show you can use a variety of things.

You could also be specific about the colours. Try ?rainbow for starters and go from there. You can specify your own or have R do it for you. As long as you use the same method for each you're OK.

How to randomly select an item from a list?

The following code demonstrates if you need to produce the same items. You can also specify how many samples you want to extract.
The sample method returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples.

import random as random
random.seed(0)  # don't use seed function, if you want different results in each run
print(random.sample(foo,3))  # 3 is the number of sample you want to retrieve

Output:['d', 'e', 'a']

OSError: [WinError 193] %1 is not a valid Win32 application

The file hello.py is not an executable file. You need to specify a file like python.exe

try following:

import sys
subprocess.call([sys.executable, 'hello.py', 'htmlfilename.htm'])

How to SHUTDOWN Tomcat in Ubuntu?

To stop apache process try this command

ps aux | grep tomcat | awk '{print $2}' | xargs kill -9

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

You should have added muted attribute inside your videoElement for your code work as expected. Look bellow ..

<video id="IPcamerastream" muted="muted" autoplay src="videoplayback%20(1).mp4" width="960" height="540"></video>

Don' t forget to add a valid video link as source

How to split a comma-separated string?

Remove all white spaces and create an fixed-size or immutable List (See asList API docs)

final String str = "dog, cat, bear, elephant, ..., giraffe";
List<String> list = Arrays.asList(str.replaceAll("\\s", "").split(","));
// result: [dog, cat, bear, elephant, ..., giraffe]

It is possible to also use replaceAll(\\s+", "") but maximum efficiency depends on the use case. (see @GurselKoca answer to Removing whitespace from strings in Java)

Global Git ignore

If you're using VSCODE, you can get this extension to handle the task for you. It watches your workspace each time you save your work and helps you to automatically ignore the files and folders you specified in your vscode settings.json ignoreit (vscode extension)

How do you wait for input on the same Console.WriteLine() line?

As Matt has said, use Console.Write. I would also recommend explicitly flushing the output, however - I believe WriteLine does this automatically, but I'd seen oddities when just using Console.Write and then waiting. So Matt's code becomes:

Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();

Synchronously waiting for an async operation, and why does Wait() freeze the program here

The await inside your asynchronous method is trying to come back to the UI thread.

Since the UI thread is busy waiting for the entire task to complete, you have a deadlock.

Moving the async call to Task.Run() solves the issue.
Because the async call is now running on a thread pool thread, it doesn't try to come back to the UI thread, and everything therefore works.

Alternatively, you could call StartAsTask().ConfigureAwait(false) before awaiting the inner operation to make it come back to the thread pool rather than the UI thread, avoiding the deadlock entirely.

Does Python have a ternary conditional operator?

Other answers correctly talk about the Python ternary operator. I would like to complement by mentioning a scenario for which the ternary operator is often used but for which there is a better idiom. This is the scenario of using a default value.

Suppose we want to use option_value with a default value if it is not set:

run_algorithm(option_value if option_value is not None else 10)

or, if option_value is never set to a falsy value (0, "", etc), simply

run_algorithm(option_value if option_value else 10)

However, in this case an ever better solution is simply to write

run_algorithm(option_value or 10)

jQuery plugin returning "Cannot read property of undefined"

I had same problem with 'parallax' plugin. I changed jQuery librery version to *jquery-1.6.4* from *jquery-1.10.2*. And error cleared.

setting system property

You can do this via a couple ways.

One is when you run your application, you can pass it a flag.

java -Dgate.home="http://gate.ac.uk/wiki/code-repository" your_application

Or set it programmatically in code before the piece of code that needs this property set. Java keeps a Properties object for System wide configuration.

Properties props = System.getProperties();
props.setProperty("gate.home", "http://gate.ac.uk/wiki/code-repository");

'Linker command failed with exit code 1' when using Google Analytics via CocoaPods

I had this same issue. Fortunately you can use Google Analytics with BitCode enabled, but it's a bit confusing due to how Google had set up their CocoaPods support.

There's actually 2 CocoaPods you can use:

  • 'Google/Analytics'
  • 'GoogleAnalytics'

The first one is the "latest" but it's tied to the greater Google pods so it does not support Bitcode. The second one is for Analytics only and does support BitCode. However because the latter does not include extra Google pods some of the instructions on how to set it up are incorrect.

You have to use the v2 method of setting up analytics:

// Inside AppDelegate:

// Optional: automatically send uncaught exceptions to Google Analytics.
GAI.sharedInstance().trackUncaughtExceptions = true

// Optional: set Google Analytics dispatch interval to e.g. 20 seconds.
GAI.sharedInstance().dispatchInterval = 20

// Create tracker instance.
let tracker = GAI.sharedInstance().trackerWithTrackingId("XX-XXXXXXXX-Y")

The rest of the Google analytics api you can use the v3 documentation (you don't need to use v2).

The 'Google/Analytics' cocoapod as of this writing still does not support BitCode. See here

Using if elif fi in shell scripts

Change [ to [[, and ] to ]].

How to force Chrome's script debugger to reload javascript?

If you're running a local server on Apache, you can get what look like caching problems. This happened to me when I had a Apache server running under Vagrant (in virtualbox).

Just add the following lines to your config file (/etc/httpd/conf/httpd.conf or equivalent):

#Disable image serving for network mounted drive
EnableSendfile off

Note that it's worth searching through the config file to see if EnableSendfile is set to on anywhere else.

How do you split and unsplit a window/view in Eclipse IDE?

This is possible with the menu items Window>Editor>Toggle Split Editor.

Current shortcut for splitting is:

Azerty keyboard:

  • Ctrl + _ for split horizontally, and
  • Ctrl + { for split vertically.

Qwerty US keyboard:

  • Ctrl + Shift + - (accessing _) for split horizontally, and
  • Ctrl + Shift + [ (accessing {) for split vertically.

MacOS - Qwerty US keyboard:

  • + Shift + - (accessing _) for split horizontally, and
  • + Shift + [ (accessing {) for split vertically.

On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:

  • Alt + ASCII code + Ctrl then release Alt

Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.

Example of vertical split:

https://bugs.eclipse.org/bugs/attachment.cgi?id=238285

PS:

  • The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
  • The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
  • The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.

CSS Selector "(A or B) and C"?

If you have this:

<div class="a x">Foo</div>
<div class="b x">Bar</div>
<div class="c x">Baz</div>

And you only want to select the elements which have .x and (.a or .b), you could write:

.x:not(.c) { ... }

but that's convenient only when you have three "sub-classes" and you want to select two of them.

Selecting only one sub-class (for instance .a): .a.x

Selecting two sub-classes (for instance .a and .b): .x:not(.c)

Selecting all three sub-classes: .x

How to get hex color value rather than RGB value?

Function that returns background color of an element in hex.

function getBgColorHex(elem){
    var color = elem.css('background-color')
    var hex;
    if(color.indexOf('#')>-1){
        //for IE
        hex = color;
    } else {
        var rgb = color.match(/\d+/g);
        hex = '#'+ ('0' + parseInt(rgb[0], 10).toString(16)).slice(-2) + ('0' + parseInt(rgb[1], 10).toString(16)).slice(-2) + ('0' + parseInt(rgb[2], 10).toString(16)).slice(-2);
    }
    return hex;
}

usage example:

$('#div1').click(function(){
   alert(getBgColorHex($(this));
}

jsfiddle

Docker: Container keeps on restarting again on again

The docker logs command will show you the output a container is generating when you don't run it interactively. This is likely to include the error message.

docker logs --tail 50 --follow --timestamps mediawiki_web_1

You can also run a fresh container in the foreground with docker run -ti <your_wiki_image> to see what that does. You may need to map some config from your docker-compose yml to the docker command.

I would guess that attaching to the media wiki process caused a crash which has corrupted something in your data.

How to avoid a System.Runtime.InteropServices.COMException?

Probably you are trying to access the excel with the index 0, please note that Excel rows/columns start from 1.

Simple linked list in C++

I'll join the fray. It's been too long since I've written C. Besides, there's no complete examples here anyway. The OP's code is basically C, so I went ahead and made it work with GCC.

The problems were covered before; the next pointer wasn't being advanced. That was the crux of the issue.

I also took the opportunity to make a suggested edit; instead of having two funcitons to malloc, I put it in initNode() and then used initNode() to malloc both (malloc is "the C new" if you will). I changed initNode() to return a pointer.

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

// required to be declared before self-referential definition
struct Node;

struct Node {
    int x;
    struct Node *next;
};

struct Node* initNode( int n){
    struct Node *head = malloc(sizeof(struct Node));
    head->x = n;
    head->next = NULL;
    return head;
}

void addNode(struct Node **head, int n){
 struct Node *NewNode = initNode( n );
 NewNode -> next = *head;
 *head = NewNode;
}

int main(int argc, char* argv[])
{
    struct Node* head = initNode(5);
    addNode(&head,10);
    addNode(&head,20);
    struct Node* cur  = head;
    do {
        printf("Node @ %p : %i\n",(void*)cur, cur->x );
    } while ( ( cur = cur->next ) != NULL );

}

compilation: gcc -o ll ll.c

output:

Node @ 0x9e0050 : 20
Node @ 0x9e0030 : 10
Node @ 0x9e0010 : 5

What is the purpose of the word 'self'?

I will demonstrate with code that does not use classes:

def state_init(state):
    state['field'] = 'init'

def state_add(state, x):
    state['field'] += x

def state_mult(state, x):
    state['field'] *= x

def state_getField(state):
    return state['field']

myself = {}
state_init(myself)
state_add(myself, 'added')
state_mult(myself, 2)

print( state_getField(myself) )
#--> 'initaddedinitadded'

Classes are just a way to avoid passing in this "state" thing all the time (and other nice things like initializing, class composition, the rarely-needed metaclasses, and supporting custom methods to override operators).

Now let's demonstrate the above code using the built-in python class machinery, to show how it's basically the same thing.

class State(object):
    def __init__(self):
        self.field = 'init'
    def add(self, x):
        self.field += x
    def mult(self, x):
        self.field *= x

s = State()
s.add('added')    # self is implicitly passed in
s.mult(2)         # self is implicitly passed in
print( s.field )

[migrated my answer from duplicate closed question]

Updating Python on Mac

I personally wouldn't mess around with OSX's python like they said. My personally preference for stuff like this is just using MacPorts and installing the versions I want via command line. MacPorts puts everything into a separate direction (under /opt I believe), so it doesn't override or directly interfere with the regular system. It has all the usually features of any package management utilities if you are familiar with Linux distros.

I would also suggest installing python_select via MacPorts and using that to select which python you want "active" (it will change the symlinks to point to the version you want). So at any time you can switch back to the Apple maintained version of python that came with OSX or you can switch to any of the ones installed via MacPorts.

Splitting String with delimiter

Try:

def (value1, value2) = '1128-2'.tokenize( '-' )

What is "String args[]"? parameter in main method Java

Explanation in simple layman's language.

The main method expects us to provide some arguments when we direct our JVM to the class name. That means, suppose your file name is Try.java, now to execute this in command prompt you write "javac Try.java" to compile followed by "java Try" to execute. Now suppose instead of writing simply "java Try" you write "java Try 1". Here you have passed an argument "1". This will be taken by your main method even if you don't use it in your code.

If you want to check whether your main method has actually taken the argument "1" or not. Simply, inside your main method type the following:

for(int i = 0; i < args.length; i++) {
        System.out.println("Argument is: "+args[i]);
    }

Forward request headers from nginx proxy server

If you want to pass the variable to your proxy backend, you have to set it with the proxy module.

location / {
    proxy_pass                      http://example.com;
    proxy_set_header                Host example.com;
    proxy_set_header                HTTP_Country-Code $geoip_country_code;
    proxy_pass_request_headers      on;
}

And now it's passed to the proxy backend.

substring index range

Like you I didn't find it came naturally. I normally still have to remind myself that

  • the length of the returned string is

    lastIndex - firstIndex

  • that you can use the length of the string as the lastIndex even though there is no character there and trying to reference it would throw an Exception

so

"University".substring(6, 10)

returns the 4-character string "sity" even though there is no character at position 10.

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

Execute action when back bar button of UINavigationController is pressed

You can subclass UINavigationController and override popViewController(animated: Bool). Beside being able to execute some code there you can also prevent the user from going back altogether, for instance to prompt to save or discard his current work.

Sample implementation where you can set a popHandler that gets set/cleared by pushed controllers.

class NavigationController: UINavigationController
{
    var popHandler: (() -> Bool)?

    override func popViewController(animated: Bool) -> UIViewController?
    {
        guard self.popHandler?() != false else
        {
            return nil
        }
        self.popHandler = nil
        return super.popViewController(animated: animated)
    }
}

And sample usage from a pushed controller that tracks unsaved work.

let hasUnsavedWork: Bool = // ...
(self.navigationController as! NavigationController).popHandler = hasUnsavedWork ?
    {
        // Prompt saving work here with an alert

        return false // Prevent pop until as user choses to save or discard

    } : nil // No unsaved work, we clear popHandler to let it pop normally

As a nice touch, this will also get called by interactivePopGestureRecognizer when the user tries to go back using a swipe gesture.

How do I fix the error 'Named Pipes Provider, error 40 - Could not open a connection to' SQL Server'?

A thread on MSDN Social, Re: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server, has a pretty decent list of possible issues that are related to your error. You may want to see if any of them could be what you're experiencing.

  • Incorrect connection string, such as using SqlExpress
  • Named Pipes(NP) was not enabled on the SQL instance
  • Remote connection was not enabled
  • Server not started, or point to not a real server in your connection string
  • Other reasons such as incorrect security context
  • try basic connectivity tests between the two machines you are working on

How can I create a carriage return in my C# string

You can put \r\n in your string.

Iptables setting multiple multiports in one rule

As far as i know, writing multiple matches is logical AND operation; so what your rule means is if the destination port is "59100" AND "3000" then reject connection with tcp-reset; Workaround is using -mport option. Look out for the man page.

how to get a list of dates between two dates in java

With java 8

public Stream<LocalDate> getDaysBetween(LocalDate startDate, LocalDate endDate) {
    return IntStream.range(0, (int) DAYS.between(startDate, endDate)).mapToObj(startDate::plusDays);
}

How to beautify JSON in Python?

It looks like jsbeautifier open sourced their tools and packaged them as Python and JS libs, and as CLI tools. It doesn't look like they call out to a web service, but I didn't check too closely. See the github repo with install instructions.


From their docs for Python CLI and library usage:

To beautify using python:

$ pip install jsbeautifier
$ js-beautify file.js

Beautified output goes to stdout.

To use jsbeautifier as a library is simple:

import jsbeautifier
res = jsbeautifier.beautify('your javascript string')
res = jsbeautifier.beautify_file('some_file.js')

...or, to specify some options:

opts = jsbeautifier.default_options()
opts.indent_size = 2
res = jsbeautifier.beautify('some javascript', opts)

If you want to pass a string instead of a filename, and you are using bash, then you can use process substitution like so:

$ js-beautify <(echo '{"some": "json"}')

Java : Sort integer array without using Arrays.sort()

Simple way :

int a[]={6,2,5,1};
            System.out.println(Arrays.toString(a));
             int temp;
             for(int i=0;i<a.length-1;i++){
                 for(int j=0;j<a.length-1;j++){
                     if(a[j] > a[j+1]){   // use < for Descending order
                         temp = a[j+1];
                         a[j+1] = a[j];
                         a[j]=temp;
                     }
                 }
             }
            System.out.println(Arrays.toString(a));

    Output:
    [6, 2, 5, 1]
    [1, 2, 5, 6]

Font Awesome 5 font-family issue

If you are using SVG with JavaScript you need to enable this because it's disabled by default. Use

<script data-search-pseudo-elements ... >

inside your script tag.

How can I hide the Adobe Reader toolbar when displaying a PDF in the .NET WebBrowser control?

It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.

The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:

   Adobe Reader Preferences dialog

You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:

   Adobe Reader Read Mode toolbar button

Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:

#toolbar=0&navpanes=0

So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.

string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);

You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.

pthread_join() and pthread_exit()

The typical use is

void* ret = NULL;
pthread_t tid = something; /// change it suitably
if (pthread_join (tid, &ret)) 
   handle_error();
// do something with the return value ret

Opposite of append in jquery

The opposite of .append() is .prepend().

From the jQuery documentation for prepend…

The .prepend() method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use .append()).

I realize this doesn’t answer the OP’s specific case. But it does answer the question heading. :) And it’s the first hit on Google for “jquery opposite append”.

How to fix warning from date() in PHP"

error_reporting(E_ALL ^ E_WARNING);

:)

You should change subject to "How to fix warning from date() in PHP"...

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

Regarding whitehawk's accepted answer. I am just trying to add a bit hands on experience. Was just trying to add a comments, but SO complains it's too long.

Basically, without IE 9 installed, the registry switch FEATURE_BROWSER_EMULATION won't work AT ALL.

For example, my own experience today I was trying to get the .net webcontrol to work with IE10 mode because one html I am trying to render won't work with .netControl under VS2012, and not even work when I load the html to IE8 directly, still css won't render properly(even after I say allow blocked content). But I have tested the same html ok with IE10 on a friend's win 8 machine. That's why I am trying to set the .net webControl to IE 10 mode but just keeps failing...

Now I figured this is bcos my win 7 machine only have IE8 installed, so regardless which value I set to the FEATURE_BROWSER_EMULATION switch(value to IE9, IE10 IE11), it just won't work AT ALL !

Then I downloaded and installed IE 10 on my win 7 machine. Still it won't work, then I added the FEATURE_BROWSER_EMULATION, it started working !

Also I noticed regardless which value I set , even set it to value 0 by default, the webControl is still using IE 10 mode which still works for me.

So to summarise, If you have IE X installed but you want your .Net webControl to work under IE (X+N) N>0 modo, TWO things you need to do:

  1. Go to MS website & download and install IE (X+N) on your machine, you will need to reboot after installation.

  2. apply whitehawk's answer.

Basically: To control the value of this feature by using the registry, add the name of your executable file to the following setting and set the value to match the desired setting.

HKEY_LOCAL_MACHINE (or HKEY_CURRENT_USER)
   SOFTWARE
      Microsoft
         Internet Explorer
            Main
               FeatureControl
                  FEATURE_BROWSER_EMULATION
                     contoso.exe = (DWORD) 00009000

Windows Internet Explorer 8 and later. The FEATURE_BROWSER_EMULATION feature defines the default emulation mode for Internet Explorer and supports the following values.

Value Description

  • 11001 (0x2AF9 Internet Explorer 11. Webpages are displayed in IE11 edge mode, regardless of the !DOCTYPE directive.

    11000 (0x2AF8) IE11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 edge mode. Default value for IE11.

    10001 (0x2711) Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive.

    10000 (0x02710) Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10.

    9999 (0x270F) Windows Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the !DOCTYPE directive.

    9000 (0x2328) Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. Default value for Internet Explorer 9.

    Important In Internet Explorer 10, Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode.

    8888 (0x22B8) Webpages are displayed in IE8 Standards mode, regardless of the !DOCTYPE directive.

    8000 (0x1F40) Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. Default value for Internet Explorer 8 Important In Internet Explorer 10, Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode.

    7000 (0x1B58) Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. Default value for applications hosting the WebBrowser Control.

Full ref here

How to use hex color values

UIColor:

extension UIColor {

    convenience init(hex: Int) {
        let components = (
            R: CGFloat((hex >> 16) & 0xff) / 255,
            G: CGFloat((hex >> 08) & 0xff) / 255,
            B: CGFloat((hex >> 00) & 0xff) / 255
        )
        self.init(red: components.R, green: components.G, blue: components.B, alpha: 1)
    }

}

CGColor:

extension CGColor {

    class func colorWithHex(hex: Int) -> CGColorRef {

        return UIColor(hex: hex).CGColor

    }

}

Usage

let purple = UIColor(hex: 0xAB47BC)

Angular 2.0 and Modal Dialog

Here's a pretty decent example of how you can use the Bootstrap modal within an Angular2 app on GitHub.

The gist of it is that you can wrap the bootstrap html and jquery initialization in a component. I've created a reusable modal component that allows you to trigger an open using a template variable.

<button type="button" class="btn btn-default" (click)="modal.open()">Open me!</button>

<modal #modal>
    <modal-header [show-close]="true">
        <h4 class="modal-title">I'm a modal!</h4>
    </modal-header>
    <modal-body>
        Hello World!
    </modal-body>
    <modal-footer [show-default-buttons]="true"></modal-footer>
</modal>

You just need to install the npm package and register the modal module in your app module:

import { Ng2Bs3ModalModule } from 'ng2-bs3-modal/ng2-bs3-modal';

@NgModule({
    imports: [Ng2Bs3ModalModule]
})
export class MyAppModule {}

How to convert a String to long in javascript?

JavaScript has a Number type which is a 64 bit floating point number*.

If you're looking to convert a string to a number, use

  1. either parseInt or parseFloat. If using parseInt, I'd recommend always passing the radix too.
  2. use the Unary + operator e.g. +"123456"
  3. use the Number constructor e.g. var n = Number("12343")

*there are situations where the number will internally be held as an integer.

How to stop Python closing immediately when executed in Microsoft Windows

Put

input('Press ENTER to exit') 

at the end to have it stop.

Which port(s) does XMPP use?

According to Extensible Messaging and Presence Protocol (Wikipedia), the standard TCP port for the server is 5222.

The client would presumably use the same ports as the messaging protocol, but can also use http (port 80) and https (port 443) for message delivery. These have the advantage of working for users behind firewalls, so your network admin should not need to get involved.

OnItemClickListener using ArrayAdapter for ListView

you can use this way...

listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                final int position, long id) {

          String main = listView.getSelectedItem().toString();
        }
    });

Remove Primary Key in MySQL

ALTER TABLE `table_name` ADD PRIMARY KEY( `column_name`);

How can I disable ReSharper in Visual Studio and enable it again?

Bind ReSharper_ToggleSuspended to a shortcut key.

Steps:

  1. Tools>Options
  2. Click Keyboard on the left hand side
  3. Type "suspend" in the "Show commands containing:" input box
  4. Pick the "ReSharper_ToggleSuspended"
  5. Press shortcut keys: and
  6. Press the "Assign" button.

Binding ReSharper_ToggleSuspended to a shortcut key (in my case: Ctrl-Shift-Q) works very well. With ReSharper not supporting the async CTP yet (as of mid-2011), when dipping into the code the uses the async keyword, this shortcut is invaluable.

pandas how to check dtype for all columns in a dataframe?

Suppose df is a pandas DataFrame then to get number of non-null values and data types of all column at once use:

df.info()

Enable IIS7 gzip

Configuration

You can enable GZIP compression entirely in your Web.config file. This is particularly useful if you're on shared hosting and can't configure IIS directly, or you want your config to carry between all environments you target.

<system.webServer>
  <httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
    <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
    <dynamicTypes>
      <add mimeType="text/*" enabled="true"/>
      <add mimeType="message/*" enabled="true"/>
      <add mimeType="application/javascript" enabled="true"/>
      <add mimeType="*/*" enabled="false"/>
    </dynamicTypes>
    <staticTypes>
      <add mimeType="text/*" enabled="true"/>
      <add mimeType="message/*" enabled="true"/>
      <add mimeType="application/javascript" enabled="true"/>
      <add mimeType="*/*" enabled="false"/>
    </staticTypes>
  </httpCompression>
  <urlCompression doStaticCompression="true" doDynamicCompression="true"/>
</system.webServer>

Testing

To test whether compression is working or not, use the developer tools in Chrome or Firebug for Firefox and ensure the HTTP response header is set:

Content-Encoding: gzip

Note that this header won't be present if the response code is 304 (Not Modified). If that's the case, do a full refresh (hold shift or control while you press the refresh button) and check again.

AndroidStudio: Failed to sync Install build tools

I was also facing the same problem with gradle. Now I have solved by installing the highlighted in red. To navigate on this page Open Android studio > Tool > Android > SDK Manager > Appearance & Behavior > System Settings > Android SDK > SDK Tools (from tab options) > Show Package details(check box on the right bottom corner). After installing these just refresh the gradle everything will be resolved.sdk download screenshot

Can you have a <span> within a <span>?

Yes. You can have a span within a span. Your problem stems from something else.

jQuery select change event get selected option

You can use the jQuery find method

 $('select').change(function () {
     var optionSelected = $(this).find("option:selected");
     var valueSelected  = optionSelected.val();
     var textSelected   = optionSelected.text();
 });

The above solution works perfectly but I choose to add the following code for them willing to get the clicked option. It allows you get the selected option even when this select value has not changed. (Tested with Mozilla only)

    $('select').find('option').click(function () {
     var optionSelected = $(this);
     var valueSelected  = optionSelected.val();
     var textSelected   = optionSelected.text();
   });

List of macOS text editors and code editors

I use Eclipse as my primary editor (for Python) but I always keep SubEthaEdit handy as my supplemental text editor (free trial, 30 euros to license). It's not super-complicated but it does what I need.

What is a "slug" in Django?

A "slug" is a way of generating a valid URL, generally using data already obtained. For instance, a slug uses the title of an article to generate a URL. I advise to generate the slug by means of a function, given the title (or another piece of data), rather than setting it manually.

An example:

<title> The 46 Year Old Virgin </title>
<content> A silly comedy movie </content>
<slug> the-46-year-old-virgin </slug>

Now let's pretend that we have a Django model such as:

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(max_length=1000)
    slug = models.SlugField(max_length=40)

How would you reference this object with a URL and with a meaningful name? You could for instance use Article.id so the URL would look like this:

www.example.com/article/23

Or, you might want to reference the title like this:

www.example.com/article/The 46 Year Old Virgin

Since spaces aren't valid in URLs, they must be replaced by %20, which results in:

www.example.com/article/The%2046%20Year%20Old%20Virgin

Both attempts are not resulting in very meaningful, easy-to-read URL. This is better:

www.example.com/article/the-46-year-old-virgin

In this example, the-46-year-old-virgin is a slug: it is created from the title by down-casing all letters, and replacing spaces by hyphens -.

Also see the URL of this very web page for another example.

How can I check if a background image is loaded?

There are no JS callbacks for CSS assets.

Is it possible to sort a ES6 map object?

The snippet below sorts given map by its keys and maps the keys to key-value objects again. I used localeCompare function since my map was string->string object map.

var hash = {'x': 'xx', 't': 'tt', 'y': 'yy'};
Object.keys(hash).sort((a, b) => a.localeCompare(b)).map(function (i) {
            var o = {};
            o[i] = hash[i];
            return o;
        });

result: [{t:'tt'}, {x:'xx'}, {y: 'yy'}];

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

Solution for per-app deployments

This is a listener I wrote to solve the problem: it autodetects if the driver has registered itself and acts accordingly.it

Important: it is meant to be used ONLY when the driver jar is deployed in WEB-INF/lib, not in the Tomcat /lib, as many suggest, so that each application can take care of its own driver and run on a untouched Tomcat. That is the way it should be IMHO.

Just configure the listener in your web.xml before any other and enjoy.

add near the top of web.xml:

<listener>
    <listener-class>utils.db.OjdbcDriverRegistrationListener</listener-class>    
</listener>

save as utils/db/OjdbcDriverRegistrationListener.java:

package utils.db;

import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import oracle.jdbc.OracleDriver;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Registers and unregisters the Oracle JDBC driver.
 * 
 * Use only when the ojdbc jar is deployed inside the webapp (not as an
 * appserver lib)
 */
public class OjdbcDriverRegistrationListener implements ServletContextListener {

    private static final Logger LOG = LoggerFactory
            .getLogger(OjdbcDriverRegistrationListener.class);

    private Driver driver = null;

    /**
     * Registers the Oracle JDBC driver
     */
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        this.driver = new OracleDriver(); // load and instantiate the class
        boolean skipRegistration = false;
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements()) {
            Driver driver = drivers.nextElement();
            if (driver instanceof OracleDriver) {
                OracleDriver alreadyRegistered = (OracleDriver) driver;
                if (alreadyRegistered.getClass() == this.driver.getClass()) {
                    // same class in the VM already registered itself
                    skipRegistration = true;
                    this.driver = alreadyRegistered;
                    break;
                }
            }
        }

        try {
            if (!skipRegistration) {
                DriverManager.registerDriver(driver);
            } else {
                LOG.debug("driver was registered automatically");
            }
            LOG.info(String.format("registered jdbc driver: %s v%d.%d", driver,
                    driver.getMajorVersion(), driver.getMinorVersion()));
        } catch (SQLException e) {
            LOG.error(
                    "Error registering oracle driver: " + 
                            "database connectivity might be unavailable!",
                    e);
            throw new RuntimeException(e);
        }
    }

    /**
     * Deregisters JDBC driver
     * 
     * Prevents Tomcat 7 from complaining about memory leaks.
     */
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        if (this.driver != null) {
            try {
                DriverManager.deregisterDriver(driver);
                LOG.info(String.format("deregistering jdbc driver: %s", driver));
            } catch (SQLException e) {
                LOG.warn(
                        String.format("Error deregistering driver %s", driver),
                        e);
            }
            this.driver = null;
        } else {
            LOG.warn("No driver to deregister");
        }

    }

}

How to find most common elements of a list?

If you are using Count, or have created your own Count-style dict and want to show the name of the item and the count of it, you can iterate around the dictionary like so:

top_10_words = Counter(my_long_list_of_words)
# Iterate around the dictionary
for word in top_10_words:
        # print the word
        print word[0]
        # print the count
        print word[1]

or to iterate through this in a template:

{% for word in top_10_words %}
        <p>Word: {{ word.0 }}</p>
        <p>Count: {{ word.1 }}</p>
{% endfor %}

Hope this helps someone

Adding n hours to a date in Java?

You can do it with Joda DateTime API

DateTime date= new DateTime(dateObj);
date = date.plusHours(1);
dateObj = date.toDate();

Can you center a Button in RelativeLayout?

Try

android:layout_centerHorizontal="true"

Exactly like this, it works for me:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:background="#ff0000">

    <Button
        android:id="@+id/btn_mybutton"
        android:layout_height="wrap_content"
        android:layout_width="124dip"
        android:layout_marginTop="5dip"
        android:layout_centerHorizontal="true"/>

</RelativeLayout>

Add key value pair to all objects in array

You may also try this:

arrOfObj.forEach(function(item){item.isActive = true;});

console.log(arrOfObj);

Simplest way to merge ES6 Maps/Sets?

merge to Map

 let merge = {...map1,...map2};

My httpd.conf is empty

It seems to me, that it is by design that this file is empty.

A similar question has been asked here: https://stackoverflow.com/questions/2567432/ubuntu-apache-httpd-conf-or-apache2-conf

So, you should have a look for /etc/apache2/apache2.conf

How to capture multiple repeated groups?

With one group in the pattern, you can only get one exact result in that group. If your capture group gets repeated by the pattern (you used the + quantifier on the surrounding non-capturing group), only the last value that matches it gets stored.

You have to use your language's regex implementation functions to find all matches of a pattern, then you would have to remove the anchors and the quantifier of the non-capturing group (and you could omit the non-capturing group itself as well).

Alternatively, expand your regex and let the pattern contain one capturing group per group you want to get in the result:

^([A-Z]+),([A-Z]+),([A-Z]+)$

"No resource identifier found for attribute 'showAsAction' in package 'android'"

If you are building with Eclipse, make sure your project's build target is set to Honeycomb too.

How to initialize java.util.date to empty

Try initializing with null value.

private java.util.Date date2 = null;

Also private java.util.Date date2 = ""; will not work as "" is a string.

Table and Index size in SQL Server

The exec sp_spaceused without parameter shows the summary for the whole database. The foreachtable solution generates one result set per table - which SSMS might not be able to handle if you have too many tables.

I created a script which collects the table infos via sp_spaceused and displays a summary in a single record set, sorted by size.

create table #t
(
  name nvarchar(128),
  rows varchar(50),
  reserved varchar(50),
  data varchar(50),
  index_size varchar(50),
  unused varchar(50)
)

declare @id nvarchar(128)
declare c cursor for
select '[' + sc.name + '].[' + s.name + ']' FROM sysobjects s INNER JOIN sys.schemas sc ON s.uid = sc.schema_id where s.xtype='U'

open c
fetch c into @id

while @@fetch_status = 0 begin

  insert into #t
  exec sp_spaceused @id

  fetch c into @id
end

close c
deallocate c

select * from #t
order by convert(int, substring(data, 1, len(data)-3)) desc

drop table #t

Run javascript script (.js file) in mongodb including another file inside js

for running mutilple js files

#!/bin/bash
cd /root/migrate/

ls -1 *.js | sed 's/.js$//' | while read name; do
     start=`date +%s`
     mongo localhost:27017/wbars $name.js;
     end=`date +%s`
     runtime1=$((end-start))
     runtime=$(printf '%dh:%dm:%ds\n' $(($runtime1/3600)) $(($secs%3600/60)) $(($secs%60)))
     echo @@@@@@@@@@@@@ $runtime $name.js completed @@@@@@@@@@@
     echo "$name.js completed"
     sync
     echo 1 > /proc/sys/vm/drop_caches
     echo 2 > /proc/sys/vm/drop_caches
     echo 3 > /proc/sys/vm/drop_caches
done

Differences between JDK and Java SDK

Taken from the Java EE 6 SDK Installer, shows what SDK 6 contains besides JDK:

What SDK 6 contains, besides JDK

load and execute order of scripts

After testing many options I've found that the following simple solution is loading the dynamically loaded scripts in the order in which they are added in all modern browsers

loadScripts(sources) {
    sources.forEach(src => {
        var script = document.createElement('script');
        script.src = src;
        script.async = false; //<-- the important part
        document.body.appendChild( script ); //<-- make sure to append to body instead of head 
    });
}

loadScripts(['/scr/script1.js','src/script2.js'])

Get MAC address using shell script

I know that is a little bit dated, but with basic commands, we can take the mac address of an interface:

ip link show eth0 | grep link/ether | awk '{print $2}'

Have a nice day!

How to remove RVM (Ruby Version Manager) from my system

There's a simple command built-in that will pull it:

rvm implode

This will remove the rvm/ directory and all the rubies built within it. In order to remove the final trace of rvm, you need to remove the rvm gem, too:

gem uninstall rvm

If you've made modifications to your PATH you might want to pull those, too. Check your .bashrc, .profile and .bash_profile files, among other things.

You may also have an /etc/rvmrc file, or one in your home directory ~/.rvmrc that may need to be removed as well.

Reverse each individual word of "Hello World" string with Java

if its to reverse each letter than this for loop works nicely:

for(int i = 0; i < input.length(); i++){
    output = output + input.substring((input.length()-i)-1, input.length()-i);
}

CASE (Contains) rather than equal statement

CASE WHEN ', ' + dbo.Table.Column +',' LIKE '%, lactulose,%' 
  THEN 'BP Medication' ELSE '' END AS [BP Medication]

The leading ', ' and trailing ',' are added so that you can handle the match regardless of where it is in the string (first entry, last entry, or anywhere in between).

That said, why are you storing data you want to search on as a comma-separated string? This violates all kinds of forms and best practices. You should consider normalizing your schema.

In addition: don't use 'single quotes' as identifier delimiters; this syntax is deprecated. Use [square brackets] (preferred) or "double quotes" if you must. See "string literals as column aliases" here: http://msdn.microsoft.com/en-us/library/bb510662%28SQL.100%29.aspx

EDIT If you have multiple values, you can do this (you can't short-hand this with the other CASE syntax variant or by using something like IN()):

CASE 
  WHEN ', ' + dbo.Table.Column +',' LIKE '%, lactulose,%' 
  WHEN ', ' + dbo.Table.Column +',' LIKE '%, amlodipine,%' 
  THEN 'BP Medication' ELSE '' END AS [BP Medication]

If you have more values, it might be worthwhile to use a split function, e.g.

USE tempdb;
GO

CREATE FUNCTION dbo.SplitStrings(@List NVARCHAR(MAX))
RETURNS TABLE
AS
   RETURN ( SELECT DISTINCT Item FROM
       ( SELECT Item = x.i.value('(./text())[1]', 'nvarchar(max)')
         FROM ( SELECT [XML] = CONVERT(XML, '<i>'
         + REPLACE(@List,',', '</i><i>') + '</i>').query('.')
           ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y
       WHERE Item IS NOT NULL
   );
GO

CREATE TABLE dbo.[Table](ID INT, [Column] VARCHAR(255));
GO

INSERT dbo.[Table] VALUES
(1,'lactulose, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,'),
(2,'lactulite, Lasix (furosemide), lactulose, propranolol, rabeprazole, sertraline,'),
(3,'lactulite, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,'),
(4,'lactulite, Lasix (furosemide), lactulose, amlodipine, rabeprazole, sertraline,');

SELECT t.ID
  FROM dbo.[Table] AS t
  INNER JOIN dbo.SplitStrings('lactulose,amlodipine') AS s
  ON ', ' + t.[Column] + ',' LIKE '%, ' + s.Item + ',%'
  GROUP BY t.ID;
GO

Results:

ID
----
1
2
4

Getting Index of an item in an arraylist;

To find the item that has a name, should I just use a for loop, and when the item is found, return the element position in the ArrayList?

Yes to the loop (either using indexes or an Iterator). On the return value, either return its index, or the item iteself, depending on your needs. ArrayList doesn't have an indexOf(Object target, Comparator compare)` or similar. Now that Java is getting lambda expressions (in Java 8, ~March 2014), I expect we'll see APIs get methods that accept lambdas for things like this.

How do you make strings "XML safe"?

By either escaping those characters with htmlspecialchars, or, perhaps more appropriately, using a library for building XML documents, such as DOMDocument or XMLWriter.

Another alternative would be to use CDATA sections, but then you'd have to look out for occurrences of ]]>.

Take also into consideration that that you must respect the encoding you define for the XML document (by default UTF-8).

Iterating over a numpy array

I see that no good desciption for using numpy.nditer() is here. So, I am gonna go with one. According to NumPy v1.21 dev0 manual, The iterator object nditer, introduced in NumPy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion.

I have to calculate mean_squared_error and I have already calculate y_predicted and I have y_actual from the boston dataset, available with sklearn.

def cal_mse(y_actual, y_predicted):
    """ this function will return mean squared error
       args:
           y_actual (ndarray): np array containing target variable
           y_predicted (ndarray): np array containing predictions from DecisionTreeRegressor
       returns:
           mse (integer)
    """
    sq_error = 0
    for i in np.nditer(np.arange(y_pred.shape[0])):
        sq_error += (y_actual[i] - y_predicted[i])**2
    mse = 1/y_actual.shape[0] * sq_error
    
    return mse

Hope this helps :). for further explaination visit

Android Spinner: Get the selected item change event

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

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

Better use OnItemSelectedListener() instead:

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

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

});

This works for me.

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

Check if an element is present in a Bash array

Obvious caveats aside, if your array was actually like the one above, you could do

if [[ ${arr[*]} =~ d ]]
then
  do your thing
else
  do something
fi

Postgres "psql not recognized as an internal or external command"

Even if it is a little bit late, i solved the PATH problem by removing every space.

;C:\Program Files\PostgreSQL\9.5\bin;C:\Program Files\PostgreSQL\9.5\lib

works for me now.

jquery 3.0 url.indexOf error

@choz answer is the correct way. If you have many usages and want to make sure it works everywhere without changes you can add these small migration-snippet:

/* Migration jQuery from 1.8 to 3.x */
jQuery.fn.load = function (callback) {
    var el = $(this);

    el.on('load', callback);

    return el;
};

In this case you got no erros on other nodes e.g. on $image like in @Korsmakolnikov answer!

const $image = $('img.image').load(function() {
  $(this).doSomething();
});

$image.doSomethingElseWithTheImage();

Node Version Manager install - nvm command not found

If you are using OS X, you might have to create your .bash_profile file before running the installation command. That did it for me.

Create the profile file

touch ~/.bash_profile

Re-run the install and you'll see a relevant line in the output this time.

=> Appending source string to /Users/{username}/.bash_profile

Reload your profile (or close/re-open the Terminal window).

.  ~/.bash_profile

POST request send json data java HttpUrlConnection

I had a similar issue, I was getting 400, Bad Request only with the PUT, where as POST request was perfectly fine.

Below code worked fine for POST but was giving BAD Request for PUT:

conn.setRequestProperty("Content-Type", "application/json");
os.writeBytes(json);

After making below changes worked fine for both POST and PUT

conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
os.write(json.getBytes("UTF-8"));

How to check if a variable exists in a FreeMarker template?

I think a lot of people are wanting to be able to check to see if their variable is not empty as well as if it exists. I think that checking for existence and emptiness is a good idea in a lot of cases, and makes your template more robust and less prone to silly errors. In other words, if you check to make sure your variable is not null AND not empty before using it, then your template becomes more flexible, because you can throw either a null variable or an empty string into it, and it will work the same in either case.

<#if p?? && p?has_content>1</#if>

Let's say you want to make sure that p is more than just whitespace. Then you could trim it before checking to see if it has_content.

<#if p?? && p?trim?has_content>1</#if>

UPDATE

Please ignore my suggestion -- has_content is all that is needed, as it does a null check along with the empty check. Doing p?? && p?has_content is equivalent to p?has_content, so you may as well just use has_content.

How to unlock android phone through ADB

Below commands works both when screen is on and off

To lock the screen:

adb shell input keyevent 82 && adb shell input keyevent 26 && adb shell input keyevent 26

To lock the screen and turn it off

adb shell input keyevent 82 && adb shell input keyevent 26

To unlock the screen without pass

adb shell input keyevent 82 && adb shell input keyevent 66

To unlock the screen that has pass 1234

adb shell input keyevent 82 && adb shell input text 1234 && adb shell input keyevent 66

IBOutlet and IBAction

IBAction and IBOutlets are used to hook up your interface made in Interface Builder with your controller. If you wouldn't use Interface Builder and build your interface completely in code, you could make a program without using them. But in reality most of us use Interface Builder, once you want to get some interactivity going in your interface, you will have to use IBActions and IBoutlets.

Select a random sample of results from a query result

The SAMPLE clause will give you a random sample percentage of all rows in a table.

For example, here we obtain 25% of the rows:

SELECT * FROM emp SAMPLE(25)

The following SQL (using one of the analytical functions) will give you a random sample of a specific number of each occurrence of a particular value (similar to a GROUP BY) in a table.

Here we sample 10 of each:

SELECT * FROM (
SELECT job, sal, ROW_NUMBER()
OVER (
PARTITION BY job ORDER BY job
) SampleCount FROM emp
)
WHERE SampleCount <= 10

jQuery: select an element's class and id at the same time?

In the end the same rules as for css apply.

So I think this reference could be of some valuable use.

Given final block not properly padded

I met this issue due to operation system, simple to different platform about JRE implementation.

new SecureRandom(key.getBytes())

will get the same value in Windows, while it's different in Linux. So in Linux need to be changed to

SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(128, secureRandom);

"SHA1PRNG" is the algorithm used, you can refer here for more info about algorithms.

How can I tell if a Java integer is null?

Try this:

Integer startIn = null;

try {
  startIn = Integer.valueOf(startField.getText());
} catch (NumberFormatException e) {
  .
  .
  .
}

if (startIn == null) {
  // Prompt for value...
}

Use cell's color as condition in if statement (function)

You cannot use VBA (Interior.ColorIndex) in a formula which is why you receive the error.

It is not possible to do this without VBA.

Function YellowIt(rng As Range) As Boolean
    If rng.Interior.ColorIndex = 6 Then
        YellowIt = True
    Else
        YellowIt = False
    End If
End Function

However, I do not recommend this: it is not how user-defined VBA functions (UDFs) are intended to be used. They should reflect the behaviour of Excel functions, which cannot read the colour-formatting of a cell. (This function may not work in a future version of Excel.)

It is far better that you base a formula on the original condition (decision) that makes the cell yellow in the first place. Or, alternatively, run a Sub procedure to fill in the True or False values (although, of course, these values will no longer be linked to the original cell's formatting).

How do I fix PyDev "Undefined variable from import" errors?

For code in your project, the only way is adding a declaration saying that you expected that -- possibly protected by an if False so that it doesn't execute (the static code-analysis only sees what you see, not runtime info -- if you opened that module yourself, you'd have no indication that main was expected).

To overcome this there are some choices:

  1. If it is some external module, it's possible to add it to the forced builtins so that PyDev spawns a shell for it to obtain runtime information (see http://pydev.org/manual_101_interpreter.html for details) -- i.e.: mostly, PyDev will import the module in a shell and do a dir(module) and dir on the classes found in the module to present completions and make code analysis.

  2. You can use Ctrl+1 (Cmd+1 for Mac) in a line with an error and PyDev will present you an option to add a comment to ignore that error.

  3. It's possible to create a stub module and add it to the predefined completions (http://pydev.org/manual_101_interpreter.html also has details on that).

How do I select last 5 rows in a table without sorting?

Without an order, this is impossible. What defines the "bottom"? The following will select 5 rows according to how they are stored in the database.

SELECT TOP 5 * FROM [TableName]

Most recent previous business day in Python

Use pandas!

import datetime
# BDay is business day, not birthday...
from pandas.tseries.offsets import BDay

today = datetime.datetime.today()
print(today - BDay(4))

Since today is Thursday, Sept 26, that will give you an output of:

datetime.datetime(2013, 9, 20, 14, 8, 4, 89761)

A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error

I had the same, there was an empty new line character at the beginning. That solved it:

int i = result.indexOf("{");
result = result.substring(i);
JSONObject json = new JSONObject(result.trim()); 
System.out.println(json.toString(4));  

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

Got this error because I had the Data Source Name in User DSN instead of System DSN enter image description here

Sorting HashMap by values

You don't, basically. A HashMap is fundamentally unordered. Any patterns you might see in the ordering should not be relied on.

There are sorted maps such as TreeMap, but they traditionally sort by key rather than value. It's relatively unusual to sort by value - especially as multiple keys can have the same value.

Can you give more context for what you're trying to do? If you're really only storing numbers (as strings) for the keys, perhaps a SortedSet such as TreeSet would work for you?

Alternatively, you could store two separate collections encapsulated in a single class to update both at the same time?

Send JSON via POST in C# and Receive the JSON returned?

Using the JSON.NET NuGet package and anonymous types, you can simplify what the other posters are suggesting:

// ...

string payload = JsonConvert.SerializeObject(new
{
    agent = new
    {
        name    = "Agent Name",
        version = 1,
    },

    username = "username",
    password = "password",
    token    = "xxxxx",
});

var client = new HttpClient();
var content = new StringContent(payload, Encoding.UTF8, "application/json");

HttpResponseMessage response = await client.PostAsync(uri, content);

// ...

How to completely DISABLE any MOUSE CLICK

The easiest way to freeze the UI would be to make the AJAX call synchronous.

Usually synchronous AJAX calls defeat the purpose of using AJAX because it freezes the UI, but if you want to prevent the user from interacting with the UI, then do it.

A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm

Here is assembly code:

7f0b024734be:       48 8d 14 f5 00 00 00    lea    rdx,[rsi*8]
7f0b024734c5:       00
7f0b024734c6:       48 03 13                add    rdx,QWORD PTR [rbx]
7f0b024734c9:       48 8d 7a 10             lea    rdi,[rdx+16]
7f0b024734cd:       8b 5f 08                mov    ebx,DWORD PTR [rdi+8]
7f0b024734d0:       89 d8                   mov    eax,ebx
7f0b024734d2:       c1 f8 03                sar    eax,0x3
7f0b024734d5:       85 db                   test   ebx,ebx
7f0b024734d7:       0f 8e cb 05 00 00       jle    0x7f0b02473aa8

And what it does is:

rdx = 0x00007f0a808d4ed2 * 8; // equals 0x0003F854046A7690. WTF???
rdx = rdx + something from old gen heap; // results 0x000600007f090486
rdi = rdx + 16; // results 0x000600007f090496
ebx = something from edi address (0x000600007f090496) + 8

Well I've had a look at the address map and there is nothing mapped to 0x000600007f090496 which is why you are getting a SEGV. Are you getting the same error with 1.6.0_26 JVM? Can you try it on a 32bit JVM? Looks like a JVM issue to me. Why would it do the first rdx=0x0... * 8 thing?

Insert/Update Many to Many Entity Framework . How do I do it?

Try this one for Updating:

[HttpPost]
public ActionResult Edit(Models.MathClass mathClassModel)
{
    //get current entry from db (db is context)
    var item = db.Entry<Models.MathClass>(mathClassModel);

    //change item state to modified
    item.State = System.Data.Entity.EntityState.Modified;

    //load existing items for ManyToMany collection
    item.Collection(i => i.Students).Load();

    //clear Student items          
    mathClassModel.Students.Clear();

    //add Toner items
    foreach (var studentId in mathClassModel.SelectedStudents)
    {
        var student = db.Student.Find(int.Parse(studentId));
        mathClassModel.Students.Add(student);
    }                

    if (ModelState.IsValid)
    {
       db.SaveChanges();
       return RedirectToAction("Index");
    }

    return View(mathClassModel);
}

Case statement in MySQL

I hope this would provide you with the right solution:

Syntax:

   CASE  
        WHEN search_condition THEN statement_list  
       [WHEN search_condition THEN statement_list]....
       [ELSE statement_list]  
   END CASE

Implementation:

select id, action_heading,  
   case when
             action_type="Expense" then action_amount  
             else NULL   
             end as Expense_amt,   
    case when  
             action_type ="Income" then action_amount  
             else NULL  
             end as Income_amt  
  from tbl_transaction;

Here I am using CASE statement as it is more flexible than if-then-else. It allows more than one branch. And CASE statement is standard SQL and works in most databases.

Why do abstract classes in Java have constructors?

Implementation wise you will often see inside super() statement in subclasses constructors, something like:


public class A extends AbstractB{

  public A(...){
     super(String constructorArgForB, ...);
     ...
  }
}


Returning value from Thread

If you want the value from the calling method, then it should wait for the thread to finish, which makes using threads a bit pointless.

To directly answer you question, the value can be stored in any mutable object both the calling method and the thread both have a reference to. You could use the outer this, but that isn't going to be particularly useful other than for trivial examples.

A little note on the code in the question: Extending Thread is usually poor style. Indeed extending classes unnecessarily is a bad idea. I notice you run method is synchronised for some reason. Now as the object in this case is the Thread you may interfere with whatever Thread uses its lock for (in the reference implementation, something to do with join, IIRC).

SQLAlchemy ORDER BY DESCENDING?

You can use .desc() function in your query just like this

query = (model.Session.query(model.Entry)
        .join(model.ClassificationItem)
        .join(model.EnumerationValue)
        .filter_by(id=c.row.id)
        .order_by(model.Entry.amount.desc())
        )

This will order by amount in descending order or

query = session.query(
    model.Entry
).join(
    model.ClassificationItem
).join(
    model.EnumerationValue
).filter_by(
    id=c.row.id
).order_by(
    model.Entry.amount.desc()
)
)

Use of desc function of SQLAlchemy

from sqlalchemy import desc
query = session.query(
    model.Entry
).join(
    model.ClassificationItem
).join(
    model.EnumerationValue
).filter_by(
    id=c.row.id
).order_by(
    desc(model.Entry.amount)
)
)

For official docs please use the link or check below snippet

sqlalchemy.sql.expression.desc(column) Produce a descending ORDER BY clause element.

e.g.:

from sqlalchemy import desc

stmt = select([users_table]).order_by(desc(users_table.c.name))

will produce SQL as:

SELECT id, name FROM user ORDER BY name DESC

The desc() function is a standalone version of the ColumnElement.desc() method available on all SQL expressions, e.g.:

stmt = select([users_table]).order_by(users_table.c.name.desc())

Parameters column – A ColumnElement (e.g. scalar SQL expression) with which to apply the desc() operation.

See also

asc()

nullsfirst()

nullslast()

Select.order_by()

How to switch from the default ConstraintLayout to RelativeLayout in Android Studio

None of these solutions worked for me...seemingly until I stumbled across this setting, see image. File > Settings > Editor > Layout Editor > Check "Prefer XML Editor"

https://i.stack.imgur.com/9CHe7.png

Why should I use core.autocrlf=true in Git?

For me.

Edit .gitattributes file.

add

*.dll binary

Then everything goes well.