Programs & Examples On #Data loss

How to recover deleted rows from SQL server table?

It is possible using Apex Recovery Tool,i have successfully recovered my table rows which i accidentally deleted

if you download the trial version it will recover only 10th row

check here http://www.apexsql.com/sql_tools_log.aspx

How can I transition height: 0; to height: auto; using CSS?

Expanding on @jake's answer, the transition will go all the way to the max height value, causing an extremely fast animation - if you set the transitions for both :hover and off you can then control the crazy speed a little bit more.

So the li:hover is when the mouse enters the state and then the transition on the non-hovered property will be the mouse leave.

Hopefully this will be of some help.

e.g:

.sidemenu li ul {
   max-height: 0px;
   -webkit-transition: all .3s ease;
   -moz-transition: all .3s ease;
   -o-transition: all .3s ease;
   -ms-transition: all .3s ease;
   transition: all .3s ease;
}
.sidemenu li:hover ul {
    max-height: 500px;
    -webkit-transition: all 1s ease;
   -moz-transition: all 1s ease;
   -o-transition: all 1s ease;
   -ms-transition: all 1s ease;
   transition: all 1s ease;
}
/* Adjust speeds to the possible height of the list */

Here's a fiddle: http://jsfiddle.net/BukwJ/

how to write javascript code inside php

At the time the script is executed, the button does not exist because the DOM is not fully loaded. The easiest solution would be to put the script block after the form.

Another solution would be to capture the window.onload event or use the jQuery library (overkill if you only have this one JavaScript).

Anaconda Navigator won't launch (windows 10)

I tried the following @janny loco's answer first and then reset anaconda to get it to work.

Step 1:

activate root
conda update -n root conda
conda update --all

Step 2:

anaconda-navigator --reset

After running the update commands in step 1 and not seeing any success, I reset anaconda by running the command above based on what I found here.

I am not sure if it was the combination of updating conda and reseting the navigator or just one of the two. So, please try accordingly.

How do you configure an OpenFileDialog to select folders?

The Ookii Dialogs for WPF library has a class that provides an implementation of a folder browser dialog for WPF.

https://github.com/augustoproiete/ookii-dialogs-wpf

Ookii Folder Browser Dialog

There's also a version that works with Windows Forms.

number_format() with MySQL

You need this:

CONCAT(REPLACE(FORMAT(number,0),',','.'),',',SUBSTRING_INDEX(FORMAT(number,2),'.',-1))

How to display raw html code in PRE or something like it but without escaping it

xmp is the way to go, i.e.:

<xmp>
  # your code...
</xmp>

Error message "Unable to install or run the application. The application requires stdole Version 7.0.3300.0 in the GAC"

We had the same issue with our ClickOnce application that uses Interop with Microsoft Office. It happened only on a few computers in the company.

The best fix we found out was to modify MS Office installation on problematic computers (through the Programs and Features panel) and ensure that ".NET programmability feature" (not sure of the name of the component - our Microsoft_Office versions are not English) was installed for each of the MS Office applications (Excel, Word, Outlook, etc.). This seems to not be included in a default install.

Then the problem with stdole.dll was fixed.

I hope this might help.

How to write the Fibonacci Sequence?

Optimized function of finding Fibonacci by keeping list in memory

def fib(n, a=[0, 1]):
     while n > len(a):
         a.append(a[-1] + a[-2])
    return a[n-1]

print("Fibonacci of 50 - {}".format(fib(50))

How to change the hosts file on android

Probably the easiest way would be use this app Hosts Editor . You need to have root

Confirm deletion in modal / dialog using Twitter Bootstrap?

If you want to do it in the easiest shortcut, then u can do it with this plugin.


But this plugin is an alternate implementation using Bootstrap Modal. And real Bootstrap implementation is also very easy, so I don't like to use this plugin because it adds excess JS contents in the page, which will slow down the page loading time.


Idea

I like to implement it by myself by this way-

  1. If user clicks on a button to delete an item from the list, then a JS call will put Item ID (or any more essential data) in a form in the modal.
  2. Then in the pop-up, there will be 2 buttons for confirmation.

    • Yes will submit the form (with ajax or direct form submit)
    • No will just dismiss the modal

The code will be like this (using Bootstrap)-

_x000D_
_x000D_
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
<script>_x000D_
$(document).ready(function()_x000D_
{_x000D_
    $("button").click(function()_x000D_
    {_x000D_
        //Say - $('p').get(0).id - this delete item id_x000D_
        $("#delete_item_id").val( $('p').get(0).id );_x000D_
        $('#delete_confirmation_modal').modal('show');_x000D_
    });_x000D_
});_x000D_
</script>_x000D_
_x000D_
<p id="1">This is a item to delete.</p>_x000D_
_x000D_
<button type="button" class="btn btn-danger">Delete</button>_x000D_
_x000D_
<!-- Delete Modal content-->_x000D_
_x000D_
<div class="modal fade" id="delete_confirmation_modal" role="dialog" style="display: none;">_x000D_
 <div class="modal-dialog" style="margin-top: 260.5px;">_x000D_
    <div class="modal-content">_x000D_
   <div class="modal-header">_x000D_
    <button type="button" class="close" data-dismiss="modal">×</button>_x000D_
    <h4 class="modal-title">Do you really want to delete this Category?</h4>_x000D_
   </div>_x000D_
   <form role="form" method="post" action="category_delete" id="delete_data">_x000D_
    <input type="hidden" id="delete_item_id" name="id" value="12">_x000D_
    <div class="modal-footer">_x000D_
     <button type="submit" class="btn btn-danger">Yes</button>_x000D_
     <button type="button" class="btn btn-primary" data-dismiss="modal">No</button>_x000D_
    </div>_x000D_
   </form>_x000D_
  </div>_x000D_
_x000D_
 </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You should change the form action according to your requirement.

Happy coading :)

JBoss default password

If you are using Talend MDM Server, the login is: login: admin password: talend

See more: http://wiki.glitchdata.com/index.php?title=TOS:_Accessing_the_Talend_MDM_Server

This differs from the default JBoss login of admin/admin The password setup file is also login-config.xml in this case.

Is there an upper bound to BigInteger?

The first maximum you would hit is the length of a String which is 231-1 digits. It's much smaller than the maximum of a BigInteger but IMHO it loses much of its value if it can't be printed.

Set default format of datetimepicker as dd-MM-yyyy

You could easily use:

label1.Text = dateTimePicker1.Value.Date.ToString("dd/MM/yyyy")

and if you want to change '/' or '-', just add this:

label1.Text = label1.Text.Replace(".", "-")

More info about DateTimePicker.CustomFormat Property: Link

How to post pictures to instagram using API

For anyone who is searching for a solution about posting to Instagram using AWS lambda and puppeteer (chrome-aws-lambda). Noted that this solution allow you to post 1 photo for each post only. If you are not using lambda, just replace chrome-aws-lambda with puppeteer.

For the first launch of lambda, it is normal that will not work because instagram detects “Suspicious login attempt”. Just goto instagram page using your PC and approve it, everything should be fine.

Here's my code, feel free to optimize it:

// instagram.js
const chromium = require('chrome-aws-lambda');

const username = process.env.IG_USERNAME;
const password = process.env.IG_PASSWORD;

module.exports.post = async function(fileToUpload, caption){
    const browser = await chromium.puppeteer.launch({
        args: [...chromium.args, '--window-size=520,700'],
        defaultViewport: chromium.defaultViewport,
        executablePath: await chromium.executablePath,
        headless: false,
        ignoreHTTPSErrors: true,
    });
    const page = await browser.newPage();
    await page.setUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) FxiOS/7.5b3349 Mobile/14F89 Safari/603.2.4');
    await page.goto('https://www.instagram.com/', {waitUntil: 'networkidle2'});
    
    const [buttonLogIn] = await page.$x("//button[contains(., 'Log In')]");
    if (buttonLogIn) {
        await buttonLogIn.click();
    }

    await page.waitFor('input[name="username"]');
    await page.type('input[name="username"]', username)
    await page.type('input[name="password"]', password)
    await page.click('form button[type="submit"]');

    await page.waitFor(3000);
    const [buttonSaveInfo] = await page.$x("//button[contains(., 'Not Now')]");
    if (buttonSaveInfo) {
        await buttonSaveInfo.click();
    }

    await page.waitFor(3000);
    const [buttonNotificationNotNow] = await page.$x("//button[contains(., 'Not Now')]");
    const [buttonNotificationCancel] = await page.$x("//button[contains(., 'Cancel')]");
    if (buttonNotificationNotNow) {
        await buttonNotificationNotNow.click();
    } else if (buttonNotificationCancel) {
        await buttonNotificationCancel.click(); 
    }

    await page.waitFor('form[enctype="multipart/form-data"]');
    const inputUploadHandle = await page.$('form[enctype="multipart/form-data"] input[type=file]');

    await page.waitFor(5000);
    const [buttonPopUpNotNow] = await page.$x("//button[contains(., 'Not Now')]");
    const [buttonPopUpCancel] = await page.$x("//button[contains(., 'Cancel')]");
    if (buttonPopUpNotNow) {
        await buttonPopUpNotNow.click();
    } else if (buttonPopUpCancel) {
        await buttonPopUpCancel.click(); 
    }

    await page.click('[data-testid="new-post-button"]')
    await inputUploadHandle.uploadFile(fileToUpload);

    await page.waitFor(3000);
    const [buttonNext] = await page.$x("//button[contains(., 'Next')]");
    await buttonNext.click();

    await page.waitFor(3000);
    await page.type('textarea', caption);

    const [buttonShare] = await page.$x("//button[contains(., 'Share')]");
    await buttonShare.click();
    await page.waitFor(3000);

    return true;
};
// handler.js

await instagram.post('/tmp/image.png', '#text');

it must be local file path, if it is url, download it to /tmp folder first.

Use FontAwesome or Glyphicons with css :before

What you are describing is actually what FontAwesome is doing already. They apply the FontAwesome font-family to the ::before pseudo element of any element that has a class that starts with "icon-".

[class^="icon-"]:before,
[class*=" icon-"]:before {
  font-family: FontAwesome;
  font-weight: normal;
  font-style: normal;
  display: inline-block;
  text-decoration: inherit;
}

Then they use the pseudo element ::before to place the icon in the element with the class. I just went to http://fortawesome.github.com/Font-Awesome/ and inspected the code to find this:

.icon-cut:before {
  content: "\f0c4";
}

So if you are looking to add the icon again, you could use the ::after element to achieve this. Or for your second part of your question, you could use the ::after pseudo element to insert the bullet character to look like a list item. Then use absolute positioning to place it to the left, or something similar.

i:after{ content: '\2022';}

How to execute XPath one-liners from shell?

Similar to Mike's and clacke's answers, here is the python one-liner (using python >= 2.5) to get the build version from a pom.xml file that gets around the fact that pom.xml files don't normally have a dtd or default namespace, so don't appear well-formed to libxml:

python -c "import xml.etree.ElementTree as ET; \
  print(ET.parse(open('pom.xml')).getroot().find('\
  {http://maven.apache.org/POM/4.0.0}version').text)"

Tested on Mac and Linux, and doesn't require any extra packages to be installed.

How do you do a ‘Pause’ with PowerShell 2.0?

I think it is worthwhile to recap/summarize the choices here for clarity... then offer a new variation that I believe provides the best utility.

<1> ReadKey (System.Console)

write-host "Press any key to continue..."
[void][System.Console]::ReadKey($true)
  • Advantage: Accepts any key but properly excludes Shift, Alt, Ctrl modifier keys.
  • Disadvantage: Does not work in PS-ISE.

<2> ReadKey (RawUI)

Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  • Disadvantage: Does not work in PS-ISE.
  • Disadvantage: Does not exclude modifier keys.

<3> cmd

cmd /c Pause | Out-Null
  • Disadvantage: Does not work in PS-ISE.
  • Disadvantage: Visibly launches new shell/window on first use; not noticeable on subsequent use but still has the overhead

<4> Read-Host

Read-Host -Prompt "Press Enter to continue"
  • Advantage: Works in PS-ISE.
  • Disadvantage: Accepts only Enter key.

<5> ReadKey composite

This is a composite of <1> above with the ISE workaround/kludge extracted from the proposal on Adam's Tech Blog (courtesy of Nick from earlier comments on this page). I made two slight improvements to the latter: added Test-Path to avoid an error if you use Set-StrictMode (you do, don't you?!) and the final Write-Host to add a newline after your keystroke to put the prompt in the right place.

Function Pause ($Message = "Press any key to continue . . . ") {
    if ((Test-Path variable:psISE) -and $psISE) {
        $Shell = New-Object -ComObject "WScript.Shell"
        $Button = $Shell.Popup("Click OK to continue.", 0, "Script Paused", 0)
    }
    else {     
        Write-Host -NoNewline $Message
        [void][System.Console]::ReadKey($true)
        Write-Host
    }
}
  • Advantage: Accepts any key but properly excludes Shift, Alt, Ctrl modifier keys.
  • Advantage: Works in PS-ISE (though only with Enter or mouse click)
  • Disadvantage: Not a one-liner!

Run Button is Disabled in Android Studio

just to go File -> Sync Project with Gradle files then it solves problem.

How can I obtain the element-wise logical NOT of a pandas Series?

To invert a boolean Series, use ~s:

In [7]: s = pd.Series([True, True, False, True])

In [8]: ~s
Out[8]: 
0    False
1    False
2     True
3    False
dtype: bool

Using Python2.7, NumPy 1.8.0, Pandas 0.13.1:

In [119]: s = pd.Series([True, True, False, True]*10000)

In [10]:  %timeit np.invert(s)
10000 loops, best of 3: 91.8 µs per loop

In [11]: %timeit ~s
10000 loops, best of 3: 73.5 µs per loop

In [12]: %timeit (-s)
10000 loops, best of 3: 73.5 µs per loop

As of Pandas 0.13.0, Series are no longer subclasses of numpy.ndarray; they are now subclasses of pd.NDFrame. This might have something to do with why np.invert(s) is no longer as fast as ~s or -s.

Caveat: timeit results may vary depending on many factors including hardware, compiler, OS, Python, NumPy and Pandas versions.

How to install MinGW-w64 and MSYS2?

Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).

Anyways, if you're already planning on using MSYS2, there's no need for that installer.

  1. Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).

  2. After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit or MSYS2 32-bit in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).

  3. Install a toolchain

    a) for 32-bit:

    pacman -S mingw-w64-i686-gcc
    

    b) for 64-bit:

    pacman -S mingw-w64-x86_64-gcc
    
  4. install any libraries/tools you may need. You can search the repositories by doing

    pacman -Ss name_of_something_i_want_to_install
    

    e.g.

    pacman -Ss gsl
    

    and install using

    pacman -S package_name_of_something_i_want_to_install
    

    e.g.

    pacman -S mingw-w64-x86_64-gsl
    

    and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!

  5. Open a MinGW-w64 shell:

    a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"

    b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"

  6. Verify that the compiler is working by doing

    gcc -v
    

If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin or <MSYS2 root>/mingw64/bin to your PATH.

How to subtract hours from a date in Oracle so it affects the day also

you should divide hours by 24 not 11
like this:
select to_char(sysdate - 2/24, 'dd-mon-yyyy HH24') from dual

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

This seems issue with my node upgrade. How ever I solved it with the following approach.

First uninstall the cli, clear cashe, and reinstall with these commands

npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli

Then install node-pre-gyp

npm install -g node-pre-gyp

Restart your terminal and see if the issue is solved.

Running bash script from within python

If chmod not working then you also try

import os
os.system('sh script.sh')
#you can also use bash instead of sh

test by me thanks

Sorting Characters Of A C++ String

std::sort(str.begin(), str.end());

See here

Header and footer in CodeIgniter

You can use your config.php file, and also use the power of helpers in CodeIgniter.

$config['header_css'] = array('style.css','prettyPhoto.css','nivo-slider.css');
$config['header_js']  = array('core.js','core.js',
                              'jquery-1.4.1.min.js',
                              'jquery-slidedeck.pack.lite.js',
                              'jquery-prettyPhoto.js',
                              'jquery.nivo.slider.js');

Source: https://jamshidhashimi.com/dynamically-add-javascript-and-css-files-in-codeigniter-header-page/

How to rename a file using Python

os.rename(old, new)

This is found in the Python docs: http://docs.python.org/library/os.html

Git merge reports "Already up-to-date" though there is a difference

If merging branch A into branch B reports "Already up to date", reverse is not always true. It is true only if branch B is descendant of branch A, otherwise branch B simply can have changes that aren't in A.

Example:

  1. You create branches A and B off master
  2. You make some changes in master and merge these changes only into branch B (not updating or forgetting to update branch A).
  3. You make some changes in branch A and merge A to B.

At this point merging A to B reports "Already up to date" but the branches are different because branch B has updates from master while branch A does not.

json_decode() expects parameter 1 to be string, array given

Set decoding to true

Your decoding is not set to true. If you don't have access to set the source to true. The code below will fix it for you.

$WorkingArray = json_decode(json_encode($data),true);

How can I get the list of files in a directory using C or C++?

Building on what herohuyongtao posted and a few other posts:

http://www.cplusplus.com/forum/general/39766/

What is the expected input type of FindFirstFile?

How to convert wstring into string?

This is a Windows solution.

Since I wanted to pass in std::string and return a vector of strings I had to make a couple conversions.

#include <string>
#include <Windows.h>
#include <vector>
#include <locale>
#include <codecvt>

std::vector<std::string> listFilesInDir(std::string path)
{
    std::vector<std::string> names;
    //Convert string to wstring
    std::wstring search_path = std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(path);
    WIN32_FIND_DATA fd;
    HANDLE hFind = FindFirstFile(search_path.c_str(), &fd);
    if (hFind != INVALID_HANDLE_VALUE) 
    {
        do 
        {
            // read all (real) files in current folder
            // , delete '!' read other 2 default folder . and ..
            if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) 
            {
                //convert from wide char to narrow char array
                char ch[260];
                char DefChar = ' ';
                WideCharToMultiByte(CP_ACP, 0, fd.cFileName, -1, ch, 260, &DefChar, NULL);
                names.push_back(ch);
            }
        } 
        while (::FindNextFile(hFind, &fd));
        ::FindClose(hFind);
    }
    return names;
}

How can I calculate divide and modulo for integers in C#?

Read two integers from the user. Then compute/display the remainder and quotient,

// When the larger integer is divided by the smaller integer
Console.WriteLine("Enter integer 1 please :");
double a5 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter integer 2 please :");
double b5 = double.Parse(Console.ReadLine());

double div = a5 / b5;
Console.WriteLine(div);

double mod = a5 % b5;
Console.WriteLine(mod);

Console.ReadLine();

Calculating distance between two geographic locations

public double distance(Double latitude, Double longitude, double e, double f) {
        double d2r = Math.PI / 180;

        double dlong = (longitude - f) * d2r;
        double dlat = (latitude - e) * d2r;
        double a = Math.pow(Math.sin(dlat / 2.0), 2) + Math.cos(e * d2r)
                * Math.cos(latitude * d2r) * Math.pow(Math.sin(dlong / 2.0), 2)
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double d = 6367 * c;
                return d;

    }

Full width image with fixed height

Set the height of the parent element, and give that the width. Then use a background image with the rule "background-size: cover"

    .parent {
       background-image: url(../img/team/bgteam.jpg);
       background-repeat: no-repeat;
       background-position: center center;
       -webkit-background-size: cover;
       background-size: cover;
    }

Get the value in an input text box

Pure JS

txt_name.value

_x000D_
_x000D_
txt_name.onkeyup = e=> alert(txt_name.value);
_x000D_
<input type="text" id="txt_name" />
_x000D_
_x000D_
_x000D_

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

In JavaScript, arrays and collections are different, although they are somewhat similar, but here the react needs an array. You need to create an array from the collection and apply it.

let homeArray = new Array(homes.length);
let i = 0

for (var key in homes) {
    homeArray[i] =  homes[key];
    i = i + 1;
}

In NetBeans how do I change the Default JDK?

If I remember correctly, you'll need to set the netbeans_jdkhome property in your netbeans config file. Should be in your etc/netbeans.conf file.

Change project name on Android Studio

Just go to res>values>strings.xml. One line says Somethig-your name

<string name="app_name">Somethig-your name</string>

Just replace your original name to

 <string name="app_name">Your Name</string>

How to do logging in React Native?

Users with Windows and Android Studio:

You're going to find it under Logcat in Android Studio. There are a lot of logging messages that show up here, so it may be easier for you to create a filter for "ReactNativeJS" which will only show your console.log messages that are created inside your react native application.

How to present a simple alert message in java?

Assuming you already have a JFrame to call this from:

JOptionPane.showMessageDialog(frame, "thank you for using java");

See The Java Tutorials: How to Make Dialogs
See the JavaDoc

Make DateTimePicker work as TimePicker only in WinForms

If you want to do it from properties, you can do this by setting the Format property of DateTimePicker to DateTimePickerFormat.Time and ShowUpDown property to true. Also, customFormat can be set in properties.

'if' statement in jinja2 template

We need to remember that the {% endif %} comes after the {% else %}.

So this is an example:

{% if someTest %}
     <p> Something is True </p>
{% else %}
     <p> Something is False </p>
{% endif %}

How to use java.net.URLConnection to fire and handle HTTP requests?

First a disclaimer beforehand: the posted code snippets are all basic examples. You'll need to handle trivial IOExceptions and RuntimeExceptions like NullPointerException, ArrayIndexOutOfBoundsException and consorts yourself.


Preparing

We first need to know at least the URL and the charset. The parameters are optional and depend on the functional requirements.

String url = "http://example.com";
String charset = "UTF-8";  // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
String param1 = "value1";
String param2 = "value2";
// ...

String query = String.format("param1=%s&param2=%s", 
     URLEncoder.encode(param1, charset), 
     URLEncoder.encode(param2, charset));

The query parameters must be in name=value format and be concatenated by &. You would normally also URL-encode the query parameters with the specified charset using URLEncoder#encode().

The String#format() is just for convenience. I prefer it when I would need the String concatenation operator + more than twice.


Firing an HTTP GET request with (optionally) query parameters

It's a trivial task. It's the default request method.

URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
// ...

Any query string should be concatenated to the URL using ?. The Accept-Charset header may hint the server what encoding the parameters are in. If you don't send any query string, then you can leave the Accept-Charset header away. If you don't need to set any headers, then you can even use the URL#openStream() shortcut method.

InputStream response = new URL(url).openStream();
// ...

Either way, if the other side is an HttpServlet, then its doGet() method will be called and the parameters will be available by HttpServletRequest#getParameter().

For testing purposes, you can print the response body to stdout as below:

try (Scanner scanner = new Scanner(response)) {
    String responseBody = scanner.useDelimiter("\\A").next();
    System.out.println(responseBody);
}

Firing an HTTP POST request with query parameters

Setting the URLConnection#setDoOutput() to true implicitly sets the request method to POST. The standard HTTP POST as web forms do is of type application/x-www-form-urlencoded wherein the query string is written to the request body.

URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);

try (OutputStream output = connection.getOutputStream()) {
    output.write(query.getBytes(charset));
}

InputStream response = connection.getInputStream();
// ...

Note: whenever you'd like to submit a HTML form programmatically, don't forget to take the name=value pairs of any <input type="hidden"> elements into the query string and of course also the name=value pair of the <input type="submit"> element which you'd like to "press" programmatically (because that's usually been used in the server side to distinguish if a button was pressed and if so, which one).

You can also cast the obtained URLConnection to HttpURLConnection and use its HttpURLConnection#setRequestMethod() instead. But if you're trying to use the connection for output you still need to set URLConnection#setDoOutput() to true.

HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
httpConnection.setRequestMethod("POST");
// ...

Either way, if the other side is an HttpServlet, then its doPost() method will be called and the parameters will be available by HttpServletRequest#getParameter().


Actually firing the HTTP request

You can fire the HTTP request explicitly with URLConnection#connect(), but the request will automatically be fired on demand when you want to get any information about the HTTP response, such as the response body using URLConnection#getInputStream() and so on. The above examples does exactly that, so the connect() call is in fact superfluous.


Gathering HTTP response information

  1. HTTP response status:

You need an HttpURLConnection here. Cast it first if necessary.

    int status = httpConnection.getResponseCode();
  1. HTTP response headers:

     for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
         System.out.println(header.getKey() + "=" + header.getValue());
     }
    
  2. HTTP response encoding:

When the Content-Type contains a charset parameter, then the response body is likely text based and we'd like to process the response body with the server-side specified character encoding then.

    String contentType = connection.getHeaderField("Content-Type");
    String charset = null;

    for (String param : contentType.replace(" ", "").split(";")) {
        if (param.startsWith("charset=")) {
            charset = param.split("=", 2)[1];
            break;
        }
    }

    if (charset != null) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) {
            for (String line; (line = reader.readLine()) != null;) {
                // ... System.out.println(line) ?
            }
        }
    } else {
        // It's likely binary content, use InputStream/OutputStream.
    }

Maintaining the session

The server side session is usually backed by a cookie. Some web forms require that you're logged in and/or are tracked by a session. You can use the CookieHandler API to maintain cookies. You need to prepare a CookieManager with a CookiePolicy of ACCEPT_ALL before sending all HTTP requests.

// First set the default cookie manager.
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));

// All the following subsequent URLConnections will use the same cookie manager.
URLConnection connection = new URL(url).openConnection();
// ...

connection = new URL(url).openConnection();
// ...

connection = new URL(url).openConnection();
// ...

Note that this is known to not always work properly in all circumstances. If it fails for you, then best is to manually gather and set the cookie headers. You basically need to grab all Set-Cookie headers from the response of the login or the first GET request and then pass this through the subsequent requests.

// Gather all cookies on the first request.
URLConnection connection = new URL(url).openConnection();
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
// ...

// Then use the same cookies on all subsequent requests.
connection = new URL(url).openConnection();
for (String cookie : cookies) {
    connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]);
}
// ...

The split(";", 2)[0] is there to get rid of cookie attributes which are irrelevant for the server side like expires, path, etc. Alternatively, you could also use cookie.substring(0, cookie.indexOf(';')) instead of split().


Streaming mode

The HttpURLConnection will by default buffer the entire request body before actually sending it, regardless of whether you've set a fixed content length yourself using connection.setRequestProperty("Content-Length", contentLength);. This may cause OutOfMemoryExceptions whenever you concurrently send large POST requests (e.g. uploading files). To avoid this, you would like to set the HttpURLConnection#setFixedLengthStreamingMode().

httpConnection.setFixedLengthStreamingMode(contentLength);

But if the content length is really not known beforehand, then you can make use of chunked streaming mode by setting the HttpURLConnection#setChunkedStreamingMode() accordingly. This will set the HTTP Transfer-Encoding header to chunked which will force the request body being sent in chunks. The below example will send the body in chunks of 1KB.

httpConnection.setChunkedStreamingMode(1024);

User-Agent

It can happen that a request returns an unexpected response, while it works fine with a real web browser. The server side is probably blocking requests based on the User-Agent request header. The URLConnection will by default set it to Java/1.6.0_19 where the last part is obviously the JRE version. You can override this as follows:

connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); // Do as if you're using Chrome 41 on Windows 7.

Use the User-Agent string from a recent browser.


Error handling

If the HTTP response code is 4nn (Client Error) or 5nn (Server Error), then you may want to read the HttpURLConnection#getErrorStream() to see if the server has sent any useful error information.

InputStream error = ((HttpURLConnection) connection).getErrorStream();

If the HTTP response code is -1, then something went wrong with connection and response handling. The HttpURLConnection implementation is in older JREs somewhat buggy with keeping connections alive. You may want to turn it off by setting the http.keepAlive system property to false. You can do this programmatically in the beginning of your application by:

System.setProperty("http.keepAlive", "false");

Uploading files

You'd normally use multipart/form-data encoding for mixed POST content (binary and character data). The encoding is in more detail described in RFC2388.

String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

try (
    OutputStream output = connection.getOutputStream();
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
    // Send normal param.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
    writer.append(CRLF).append(param).append(CRLF).flush();

    // Send text file.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);
    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
    writer.append(CRLF).flush();
    Files.copy(textFile.toPath(), output);
    output.flush(); // Important before continuing with writer!
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

    // Send binary file.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
    writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
    writer.append("Content-Transfer-Encoding: binary").append(CRLF);
    writer.append(CRLF).flush();
    Files.copy(binaryFile.toPath(), output);
    output.flush(); // Important before continuing with writer!
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

    // End of multipart/form-data.
    writer.append("--" + boundary + "--").append(CRLF).flush();
}

If the other side is an HttpServlet, then its doPost() method will be called and the parts will be available by HttpServletRequest#getPart() (note, thus not getParameter() and so on!). The getPart() method is however relatively new, it's introduced in Servlet 3.0 (Glassfish 3, Tomcat 7, etc). Prior to Servlet 3.0, your best choice is using Apache Commons FileUpload to parse a multipart/form-data request. Also see this answer for examples of both the FileUpload and the Servelt 3.0 approaches.


Dealing with untrusted or misconfigured HTTPS sites

Sometimes you need to connect an HTTPS URL, perhaps because you're writing a web scraper. In that case, you may likely face a javax.net.ssl.SSLException: Not trusted server certificate on some HTTPS sites who doesn't keep their SSL certificates up to date, or a java.security.cert.CertificateException: No subject alternative DNS name matching [hostname] found or javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name on some misconfigured HTTPS sites.

The following one-time-run static initializer in your web scraper class should make HttpsURLConnection more lenient as to those HTTPS sites and thus not throw those exceptions anymore.

static {
    TrustManager[] trustAllCertificates = new TrustManager[] {
        new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null; // Not relevant.
            }
            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                // Do nothing. Just allow them all.
            }
            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                // Do nothing. Just allow them all.
            }
        }
    };

    HostnameVerifier trustAllHostnames = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true; // Just allow them all.
        }
    };

    try {
        System.setProperty("jsse.enableSNIExtension", "false");
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCertificates, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames);
    }
    catch (GeneralSecurityException e) {
        throw new ExceptionInInitializerError(e);
    }
}

Last words

The Apache HttpComponents HttpClient is much more convenient in this all :)


Parsing and extracting HTML

If all you want is parsing and extracting data from HTML, then better use a HTML parser like Jsoup

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

Just adding my problem i had:

$this->load->model("planning/plan_model.php");

and the .php shouldnt be there, so it should have been:

$this->load->model("planning/plan_model");

hope this helps someone

Leverage browser caching, how on apache or .htaccess?

I was doing the same thing a couple days ago. Added this to my .htaccess file:

ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/png A2592000
ExpiresByType image/x-icon A2592000
ExpiresByType text/css A86400
ExpiresByType text/javascript A86400
ExpiresByType application/x-shockwave-flash A2592000
#
<FilesMatch "\.(gif¦jpe?g¦png¦ico¦css¦js¦swf)$">
Header set Cache-Control "public"
</FilesMatch>

And now when I run google speed page, leverage browwer caching is no longer a high priority.

Hope this helps.

PHP Session Destroy on Log Out Button

First give the link of logout.php page in that logout button.In that page make the code which is given below:

Here is the code:

<?php
 session_start();
 session_destroy();
?>

When the session has started, the session for the last/current user has been started, so don't need to declare the username. It will be deleted automatically by the session_destroy method.

How can I get the value of a registry key from within a batch script?

This works if the value contains a space:

FOR /F "skip=2 tokens=1,2*" %%A IN ('REG QUERY "%KEY_NAME%" /v "%VALUE_NAME%" 2^>nul') DO (
    set ValueName=%%A
    set ValueType=%%B
    set ValueValue=%%C
)

if defined ValueName (
    echo Value Name = %ValueName%
    echo Value Type = %ValueType%
    echo Value Value = %ValueValue%
) else (
    @echo "%KEY_NAME%"\"%VALUE_NAME%" not found.
)

Can you use if/else conditions in CSS?

(Yes, old thread. But it turned up on top of a Google-search so others might be interested as well)

I guess the if/else-logic could be done with javascript, which in turn can dynamically load/unload stylesheets. I haven't tested this across browsers etc. but it should work. This will get you started:

http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml

How can I initialize base class member variables in derived class constructor?

Aggregate classes, like A in your example(*), must have their members public, and have no user-defined constructors. They are intialized with initializer list, e.g. A a {0,0}; or in your case B() : A({0,0}){}. The members of base aggregate class cannot be individually initialized in the constructor of the derived class.

(*) To be precise, as it was correctly mentioned, original class A is not an aggregate due to private non-static members

Manually map column names with class properties

For some time, the following should work:

Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;

Getting attributes of Enum's value

This should do what you need.

var enumType = typeof(FunkyAttributesEnum);
var memberInfos = enumType.GetMember(FunkyAttributesEnum.NameWithoutSpaces1.ToString());
var enumValueMemberInfo = memberInfos.FirstOrDefault(m => m.DeclaringType == enumType);
var valueAttributes = 
      enumValueMemberInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
var description = ((DescriptionAttribute)valueAttributes[0]).Description;

How to convert InputStream to FileInputStream

You need something like:

    URL resource = this.getClass().getResource("/path/to/resource.res");
    File is = null;
    try {
        is = new File(resource.toURI());
    } catch (URISyntaxException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        FileInputStream input = new FileInputStream(is);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

But it will work only within your IDE, not in runnable JAR. I had same problem explained here.

Updating MySQL primary key

If the primary key happens to be an auto_increment value, you have to remove the auto increment, then drop the primary key then re-add the auto-increment

ALTER TABLE `xx`
MODIFY `auto_increment_field` INT, 
DROP PRIMARY KEY, 
ADD PRIMARY KEY (new_primary_key);

then add back the auto increment

ALTER TABLE `xx` ADD INDEX `auto_increment_field` (auto_increment_field),
MODIFY `auto_increment_field` int auto_increment;

then set auto increment back to previous value

ALTER TABLE `xx` AUTO_INCREMENT = 5;

Is there a MessageBox equivalent in WPF?

The equivalent to WinForms' MessageBox in WPF is called System.Windows.MessageBox.

Convert double to string C++?

You can't do it directly. There are a number of ways to do it:

  1. Use a std::stringstream:

    std::ostringstream s;
    s << "(" << c1 << ", " << c2 << ")";
    storedCorrect[count] = s.str()
    
  2. Use boost::lexical_cast:

    storedCorrect[count] = "(" + boost::lexical_cast<std::string>(c1) + ", " + boost::lexical_cast<std::string>(c2) + ")";
    
  3. Use std::snprintf:

    char buffer[256];  // make sure this is big enough!!!
    snprintf(buffer, sizeof(buffer), "(%g, %g)", c1, c2);
    storedCorrect[count] = buffer;
    

There are a number of other ways, using various double-to-string conversion functions, but these are the main ways you'll see it done.

Order columns through Bootstrap4

Since column-ordering doesn't work in Bootstrap 4 beta as described in the code provided in the revisited answer above, you would need to use the following (as indicated in the codeply 4 Flexbox order demo - alpha/beta links that were provided in the answer).

<div class="container">
<div class="row">
    <div class="col-3 col-md-6">
        <div class="card card-block">1</div>
    </div>
    <div class="col-6 col-md-12  flex-md-last">
        <div class="card card-block">3</div>
    </div>
    <div class="col-3 col-md-6 ">
        <div class="card card-block">2</div>
    </div>
</div>

Note however that the "Flexbox order demo - beta" goes to an alpha codebase, and changing the codebase to Beta (and running it) results in the divs incorrectly displaying in a single column -- but that looks like a codeply issue since cutting and pasting the code out of codeply works as described.

How can I run a function from a script in command line?

Briefly, no.

You can import all of the functions in the script into your environment with source (help source for details), which will then allow you to call them. This also has the effect of executing the script, so take care.

There is no way to call a function from a shell script as if it were a shared library.

Proper use of mutexes in Python

I don't know why you're using the Window's Mutex instead of Python's. Using the Python methods, this is pretty simple:

from threading import Thread, Lock

mutex = Lock()

def processData(data):
    mutex.acquire()
    try:
        print('Do some stuff')
    finally:
        mutex.release()

while True:
    t = Thread(target = processData, args = (some_data,))
    t.start()

But note, because of the architecture of CPython (namely the Global Interpreter Lock) you'll effectively only have one thread running at a time anyway--this is fine if a number of them are I/O bound, although you'll want to release the lock as much as possible so the I/O bound thread doesn't block other threads from running.

An alternative, for Python 2.6 and later, is to use Python's multiprocessing package. It mirrors the threading package, but will create entirely new processes which can run simultaneously. It's trivial to update your example:

from multiprocessing import Process, Lock

mutex = Lock()

def processData(data):
    with mutex:
        print('Do some stuff')

if __name__ == '__main__':
    while True:
        p = Process(target = processData, args = (some_data,))
        p.start()

Two dimensional array in python

When constructing multi-dimensional lists in Python I usually use something similar to ThiefMaster's solution, but rather than appending items to index 0, then appending items to index 1, etc., I always use index -1 which is automatically the index of the last item in the array.

i.e.

arr = []

arr.append([])
arr[-1].append("aa1")
arr[-1].append("aa2")

arr.append([])
arr[-1].append("bb1")
arr[-1].append("bb2")
arr[-1].append("bb3")

will produce the 2D-array (actually a list of lists) you're after.

Merging multiple PDFs using iTextSharp in c#.net

Using iTextSharp.dll

protected void Page_Load(object sender, EventArgs e)
{
    String[] files = @"C:\ENROLLDOCS\A1.pdf,C:\ENROLLDOCS\A2.pdf".Split(',');
    MergeFiles(@"C:\ENROLLDOCS\New1.pdf", files);
}
public void MergeFiles(string destinationFile, string[] sourceFiles)
{
    if (System.IO.File.Exists(destinationFile))
        System.IO.File.Delete(destinationFile);

    string[] sSrcFile;
    sSrcFile = new string[2];

    string[] arr = new string[2];
    for (int i = 0; i <= sourceFiles.Length - 1; i++)
    {
        if (sourceFiles[i] != null)
        {
            if (sourceFiles[i].Trim() != "")
                arr[i] = sourceFiles[i].ToString();
        }
    }

    if (arr != null)
    {
        sSrcFile = new string[2];

        for (int ic = 0; ic <= arr.Length - 1; ic++)
        {
            sSrcFile[ic] = arr[ic].ToString();
        }
    }
    try
    {
        int f = 0;

        PdfReader reader = new PdfReader(sSrcFile[f]);
        int n = reader.NumberOfPages;
        Response.Write("There are " + n + " pages in the original file.");
        Document document = new Document(PageSize.A4);

        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));

        document.Open();
        PdfContentByte cb = writer.DirectContent;
        PdfImportedPage page;

        int rotation;
        while (f < sSrcFile.Length)
        {
            int i = 0;
            while (i < n)
            {
                i++;

                document.SetPageSize(PageSize.A4);
                document.NewPage();
                page = writer.GetImportedPage(reader, i);

                rotation = reader.GetPageRotation(i);
                if (rotation == 90 || rotation == 270)
                {
                    cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                }
                else
                {
                    cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                }
                Response.Write("\n Processed page " + i);
            }

            f++;
            if (f < sSrcFile.Length)
            {
                reader = new PdfReader(sSrcFile[f]);
                n = reader.NumberOfPages;
                Response.Write("There are " + n + " pages in the original file.");
            }
        }
        Response.Write("Success");
        document.Close();
    }
    catch (Exception e)
    {
        Response.Write(e.Message);
    }


}

MongoDB what are the default user and password?

For MongoDB earlier than 2.6, the command to add a root user is addUser (e.g.)

db.addUser({user:'admin',pwd:'<password>',roles:["root"]})

How can I reference a commit in an issue comment on GitHub?

If you are trying to reference a commit in another repo than the issue is in, you can prefix the commit short hash with reponame@.

Suppose your commit is in the repo named dev, and the GitLab issue is in the repo named test. You can leave a comment on the issue and reference the commit by dev@e9c11f0a (where e9c11f0a is the first 8 letters of the sha hash of the commit you want to link to) if that makes sense.

rails simple_form - hidden field - create?

Correct way (if you are not trying to reset the value of the hidden_field input) is:

f.hidden_field :method, :value => value_of_the_hidden_field_as_it_comes_through_in_your_form

Where :method is the method that when called on the object results in the value you want

So following the example above:

= simple_form_for @movie do |f|
  = f.hidden :title, "some value"
  = f.button :submit

The code used in the example will reset the value (:title) of @movie being passed by the form. If you need to access the value (:title) of a movie, instead of resetting it, do this:

= simple_form_for @movie do |f|
  = f.hidden :title, :value => params[:movie][:title]
  = f.button :submit

Again only use my answer is you do not want to reset the value submitted by the user.

I hope this makes sense.

Excel VBA Run-time error '13' Type mismatch

Diogo

Justin has given you some very fine tips :)

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

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

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

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

Option Explicit

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

20        Application.ScreenUpdating = False

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

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

50        Set ws = Sheets(name)

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

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

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

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

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

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

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

How do I set up Vim autoindentation properly for editing Python files?

A simpler option: just uncomment the following part of the configuration (which is originally commented out) in the /etc/vim/vimrc file:

    if has("autocmd")
      filetype plugin indent on
    endif

react-native :app:installDebug FAILED

I couldn't get it to work with a hardware device. I kept getting the same error, but...

For your emulator you have to choose the IntelX86 Atom System image. Then ADB will connect to your emulator and it will properly install the installDebug.apk.

This is what I had to do.

Also look at this tutorial. It helped me immensely.

https://www.youtube.com/watch?v=cnqyUnASuk8

Why is there no ForEach extension method on IEnumerable?

The discussion here gives the answer:

Actually, the specific discussion I witnessed did in fact hinge over functional purity. In an expression, there are frequently assumptions made about not having side-effects. Having ForEach is specifically inviting side-effects rather than just putting up with them. -- Keith Farmer (Partner)

Basically the decision was made to keep the extension methods functionally "pure". A ForEach would encourage side-effects when using the Enumerable extension methods, which was not the intent.

Difference between text and varchar (character varying)

There is no difference, under the hood it's all varlena (variable length array).

Check this article from Depesz: http://www.depesz.com/index.php/2010/03/02/charx-vs-varcharx-vs-varchar-vs-text/

A couple of highlights:

To sum it all up:

  • char(n) – takes too much space when dealing with values shorter than n (pads them to n), and can lead to subtle errors because of adding trailing spaces, plus it is problematic to change the limit
  • varchar(n) – it's problematic to change the limit in live environment (requires exclusive lock while altering table)
  • varchar – just like text
  • text – for me a winner – over (n) data types because it lacks their problems, and over varchar – because it has distinct name

The article does detailed testing to show that the performance of inserts and selects for all 4 data types are similar. It also takes a detailed look at alternate ways on constraining the length when needed. Function based constraints or domains provide the advantage of instant increase of the length constraint, and on the basis that decreasing a string length constraint is rare, depesz concludes that one of them is usually the best choice for a length limit.

Unprotect workbook without password

Try the below code to unprotect the workbook. It works for me just fine in excel 2010 but I am not sure if it will work in 2013.

Sub PasswordBreaker()
    'Breaks worksheet password protection.
    Dim i As Integer, j As Integer, k As Integer
    Dim l As Integer, m As Integer, n As Integer
    Dim i1 As Integer, i2 As Integer, i3 As Integer
    Dim i4 As Integer, i5 As Integer, i6 As Integer
    On Error Resume Next
    For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
    For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
    For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
    For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
    ThisWorkbook.Unprotect Chr(i) & Chr(j) & Chr(k) & _
        Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
        Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
    If ThisWorkbook.ProtectStructure = False Then
        MsgBox "One usable password is " & Chr(i) & Chr(j) & _
            Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
            Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
         Exit Sub
    End If
    Next: Next: Next: Next: Next: Next
    Next: Next: Next: Next: Next: Next
End Sub

What does the line "#!/bin/sh" mean in a UNIX shell script?

#!/bin/sh or #!/bin/bash has to be first line of the script because if you don't use it on the first line then the system will treat all the commands in that script as different commands. If the first line is #!/bin/sh then it will consider all commands as a one script and it will show the that this file is running in ps command and not the commands inside the file.

./echo.sh

ps -ef |grep echo
trainee   3036  2717  0 16:24 pts/0    00:00:00 /bin/sh ./echo.sh
root      3042  2912  0 16:24 pts/1    00:00:00 grep --color=auto echo

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

The possible reason can also be that you have not inherited Controller from ApiController. Happened with me took a while to understand the same.

How to specify preference of library path?

Add the path to where your new library is to LD_LIBRARY_PATH (it has slightly different name on Mac ...)

Your solution should work with using the -L/my/dir -lfoo options, at runtime use LD_LIBRARY_PATH to point to the location of your library.

Careful with using LD_LIBRARY_PATH - in short (from link):

..implications..:
Security: Remember that the directories specified in LD_LIBRARY_PATH get searched before(!) the standard locations? In that way, a nasty person could get your application to load a version of a shared library that contains malicious code! That’s one reason why setuid/setgid executables do neglect that variable!
Performance: The link loader has to search all the directories specified, until it finds the directory where the shared library resides – for ALL shared libraries the application is linked against! This means a lot of system calls to open(), that will fail with “ENOENT (No such file or directory)”! If the path contains many directories, the number of failed calls will increase linearly, and you can tell that from the start-up time of the application. If some (or all) of the directories are in an NFS environment, the start-up time of your applications can really get long – and it can slow down the whole system!
Inconsistency: This is the most common problem. LD_LIBRARY_PATH forces an application to load a shared library it wasn’t linked against, and that is quite likely not compatible with the original version. This can either be very obvious, i.e. the application crashes, or it can lead to wrong results, if the picked up library not quite does what the original version would have done. Especially the latter is sometimes hard to debug.

OR

Use the rpath option via gcc to linker - runtime library search path, will be used instead of looking in standard dir (gcc option):

-Wl,-rpath,$(DEFAULT_LIB_INSTALL_PATH)

This is good for a temporary solution. Linker first searches the LD_LIBRARY_PATH for libraries before looking into standard directories.

If you don't want to permanently update LD_LIBRARY_PATH you can do it on the fly on command line:

LD_LIBRARY_PATH=/some/custom/dir ./fooo

You can check what libraries linker knows about using (example):

/sbin/ldconfig -p | grep libpthread
        libpthread.so.0 (libc6, OS ABI: Linux 2.6.4) => /lib/libpthread.so.0

And you can check which library your application is using:

ldd foo
        linux-gate.so.1 =>  (0xffffe000)
        libpthread.so.0 => /lib/libpthread.so.0 (0xb7f9e000)
        libxml2.so.2 => /usr/lib/libxml2.so.2 (0xb7e6e000)
        librt.so.1 => /lib/librt.so.1 (0xb7e65000)
        libm.so.6 => /lib/libm.so.6 (0xb7d5b000)
        libc.so.6 => /lib/libc.so.6 (0xb7c2e000)
        /lib/ld-linux.so.2 (0xb7fc7000)
        libdl.so.2 => /lib/libdl.so.2 (0xb7c2a000)
        libz.so.1 => /lib/libz.so.1 (0xb7c18000)

PostgreSQL delete with inner join

DELETE 
FROM m_productprice B  
     USING m_product C 
WHERE B.m_product_id = C.m_product_id AND
      C.upc = '7094' AND                 
      B.m_pricelist_version_id='1000020';

or

DELETE 
FROM m_productprice
WHERE m_pricelist_version_id='1000020' AND 
      m_product_id IN (SELECT m_product_id 
                       FROM m_product 
                       WHERE upc = '7094'); 

What causes: "Notice: Uninitialized string offset" to appear?

The error may occur when the number of times you iterate the array is greater than the actual size of the array. for example:

 $one="909";
 for($i=0;$i<10;$i++)
    echo ' '.$one[$i];

will show the error. first case u can take the mod of i.. for example

function mod($i,$length){
  $m = $i % $size;
  if ($m > $size)
  mod($m,$size)
  return $m;
}

for($i=0;$i<10;$i++)
{
  $k=mod($i,3);
  echo ' '.$one[$k];
}

or might be it not an array (maybe it was a value and you tried to access it like an array) for example:

$k = 2;
$k[0];

How to change the Eclipse default workspace?

If you want to change recent workspace manually in a configurationfile org.eclipse.ui.ide.prefs exists in

eclipse > configuration > .settings > org.eclipse.ui.ide.prefs

open this file in an editor find RECENT_WORKSPACES in line #2 and in this line you can see recent workspaces and can change or even remove them.

How to implement an android:background that doesn't stretch?

I am using an ImageView in an RelativeLayout that overlays with my normal layout. No code required. It sizes the image to the full height of the screen (or any other layout you use) and then crops the picture left and right to fit the width. In my case, if the user turns the screen, the picture may be a tiny bit too small. Therefore I use match_parent, which will make the image stretch in width if too small.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/main_backgroundImage"
        android:layout_width="match_parent"
        //comment: Stretches picture in the width if too small. Use "wrap_content" does not stretch, but leaves space

        android:layout_height="match_parent"
        //in my case I always want the height filled

        android:layout_alignParentTop="true"
        android:scaleType="centerCrop"
        //will crop picture left and right, so it fits in height and keeps aspect ratio

        android:contentDescription="@string/image"
        android:src="@drawable/your_image" />

    <LinearLayout
        android:id="@+id/main_root"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    </LinearLayout>

</RelativeLayout>

How to write DataFrame to postgres table?

Starting from pandas 0.14 (released end of May 2014), postgresql is supported. The sql module now uses sqlalchemy to support different database flavors. You can pass a sqlalchemy engine for a postgresql database (see docs). E.g.:

from sqlalchemy import create_engine
engine = create_engine('postgresql://username:password@localhost:5432/mydatabase')
df.to_sql('table_name', engine)

You are correct that in pandas up to version 0.13.1 postgresql was not supported. If you need to use an older version of pandas, here is a patched version of pandas.io.sql: https://gist.github.com/jorisvandenbossche/10841234.
I wrote this a time ago, so cannot fully guarantee that it always works, buth the basis should be there). If you put that file in your working directory and import it, then you should be able to do (where con is a postgresql connection):

import sql  # the patched version (file is named sql.py)
sql.write_frame(df, 'table_name', con, flavor='postgresql')

adb is not recognized as internal or external command on windows

If you go to your android-sdk/tools folder I think you'll find a message :

The adb tool has moved to platform-tools/

If you don't see this directory in your SDK, launch the SDK and AVD Manager (execute the android tool) and install "Android SDK Platform-tools"

Please also update your PATH environment variable to include the platform-tools/ directory, so you can execute adb from any location.

So you should also add C:/android-sdk/platform-tools to you environment path. Also after you modify the PATH variable make sure that you start a new CommandPrompt window.

Unsupported Media Type in postman

You need to set the content-type in postman as JSON (application/json).

Go to the body inside your POST request, there you will find the raw option.

Right next to it, there will be a drop down, select JSON (application.json).

Convert NULL to empty string - Conversion failed when converting from a character string to uniqueidentifier

SELECT Id   'PatientId',
       ISNULL(CONVERT(varchar(50),ParentId),'')  'ParentId'
FROM Patients

ISNULL always tries to return a result that has the same data type as the type of its first argument. So, if you want the result to be a string (varchar), you'd best make sure that's the type of the first argument.


COALESCE is usually a better function to use than ISNULL, since it considers all argument data types and applies appropriate precedence rules to determine the final resulting data type. Unfortunately, in this case, uniqueidentifier has higher precedence than varchar, so that doesn't help.

(It's also generally preferred because it extends to more than two arguments)

concatenate two database columns into one resultset column

The SQL standard way of doing this would be:

SELECT COALESCE(field1, '') || COALESCE(field2, '') || COALESCE(field3, '') FROM table1

Example:

INSERT INTO table1 VALUES ('hello', null, 'world');
SELECT COALESCE(field1, '') || COALESCE(field2, '') || COALESCE(field3, '') FROM table1;

helloworld

Should Gemfile.lock be included in .gitignore?

The other answers here are correct: Yes, your Ruby app (not your Ruby gem) should include Gemfile.lock in the repo. To expand on why it should do this, read on:

I was under the mistaken notion that each env (development, test, staging, prod...) each did a bundle install to build their own Gemfile.lock. My assumption was based on the fact that Gemfile.lock does not contain any grouping data, such as :test, :prod, etc. This assumption was wrong, as I found out in a painful local problem.

Upon closer investigation, I was confused why my Jenkins build showed fetching a particular gem (ffaker, FWIW) successfully, but when the app loaded and required ffaker, it said file not found. WTF?

A little more investigation and experimenting showed what the two files do:

First it uses Gemfile.lock to go fetch all the gems, even those that won't be used in this particular env. Then it uses Gemfile to choose which of those fetched gems to actually use in this env.

So, even though it fetched the gem in the first step based on Gemfile.lock, it did NOT include in my :test environment, based on the groups in Gemfile.

The fix (in my case) was to move gem 'ffaker' from the :development group to the main group, so all env's could use it. (Or, add it only to :development, :test, as appropriate)

Is it possible to have multiple styles inside a TextView?

Spanny make SpannableString easier to use.

Spanny spanny = new Spanny("Underline text", new UnderlineSpan())
                .append("\nRed text", new ForegroundColorSpan(Color.RED))
                .append("\nPlain text");
textView.setText(spanny)

Asking the user for input until they give a valid response

You can write more general logic to allow user to enter only specific number of times, as the same use-case arises in many real-world applications.

def getValidInt(iMaxAttemps = None):
  iCount = 0
  while True:
    # exit when maximum attempt limit has expired
    if iCount != None and iCount > iMaxAttemps:
       return 0     # return as default value

    i = raw_input("Enter no")
    try:
       i = int(i)
    except ValueError as e:
       print "Enter valid int value"
    else:
       break

    return i

age = getValidInt()
# do whatever you want to do.

Sync data between Android App and webserver

If we think about today, accepted answer is too old. As we know that we have many new libraries which can help you to make this types of application.

You should learn following topics that will helps you surely:

  • SyncAdapter: The sync adapter component in your app encapsulates the code for the tasks that transfer data between the device and a server. Based on the scheduling and triggers you provide in your app, the sync adapter framework runs the code in the sync adapter component.

  • Realm: Realm is a mobile database: a replacement for SQLite & Core Data.

  • Retrofit Type-safe HTTP client for Android and Java by Square, Inc. Must Learn a-smart-way-to-use-retrofit

And your sync logic for database like: How to sync SQLite database on Android phone with MySQL database on server?

Best Luck to all new learner. :)

Delete keychain items when an app is uninstalled

C# Xamarin version

    const string FIRST_RUN = "hasRunBefore";
    var userDefaults = NSUserDefaults.StandardUserDefaults;
    if (!userDefaults.BoolForKey(FIRST_RUN))
    {
        //TODO: remove keychain items
        userDefaults.SetBool(true, FIRST_RUN);
        userDefaults.Synchronize();
    }

... and to clear records from the keychain (TODO comment above)

        var securityRecords = new[] { SecKind.GenericPassword,
                                    SecKind.Certificate,
                                    SecKind.Identity,
                                    SecKind.InternetPassword,
                                    SecKind.Key
                                };
        foreach (var recordKind in securityRecords)
        {
            SecRecord query = new SecRecord(recordKind);
            SecKeyChain.Remove(query);
        }

How to convert array to SimpleXML

The answers provided here only convert array to XML with nodes, you are not able to set attributes. I have written a php function that allows you to convert an array to php and also set attributes for particular nodes in the xml. The downside here is you have to construct an array in a particular way with few conventions (only if you want to use attributes)

The following example will allow you to set attributes in XML too.

The source can be found here: https://github.com/digitickets/lalit/blob/master/src/Array2XML.php

<?php    
$books = array(
    '@attributes' => array(
        'type' => 'fiction'
    ),
    'book' => array(
        array(
            '@attributes' => array(
                'author' => 'George Orwell'
            ),
            'title' => '1984'
        ),
        array(
            '@attributes' => array(
                'author' => 'Isaac Asimov'
            ),
            'title' => 'Foundation',
            'price' => '$15.61'
        ),
        array(
            '@attributes' => array(
                'author' => 'Robert A Heinlein'
            ),
            'title' => 'Stranger in a Strange Land',
            'price' => array(
                '@attributes' => array(
                    'discount' => '10%'
                ),
                '@value' => '$18.00'
            )
        )
    )
);
/* creates 
<books type="fiction">
  <book author="George Orwell">
    <title>1984</title>
  </book>
  <book author="Isaac Asimov">
    <title>Foundation</title>
    <price>$15.61</price>
  </book>
  <book author="Robert A Heinlein">
    <title>Stranger in a Strange Land</title>
    <price discount="10%">$18.00</price>
  </book>
</books>
*/
?>

PHP Notice: Undefined offset: 1 with array when reading data

Update in 2020 in Php7:

there is a better way to do this using the Null coalescing operator by just doing the following:

$data[$parts[0]] = $parts[1] ?? null;

get enum name from enum value

You could create a lookup method. Not the most efficient (depending on the enum's size) but it works.

public static String getNameByCode(int code){
  for(RelationActiveEnum e : RelationActiveEnum.values()){
    if(code == e.value) return e.name();
  }
  return null;
}

And call it like this:

RelationActiveEnum.getNameByCode(3);

Swift convert unix time to date and time

You can get a date with that value by using the NSDate(withTimeIntervalSince1970:) initializer:

let date = NSDate(timeIntervalSince1970: 1415637900)

What does it mean when Statement.executeUpdate() returns -1?

This doesn't explain why it should be like that, but it explains why it could happen. The following byte-code sets -1 to the internal updateCount flag in the SQLServerStatement constructor:

// Method descriptor #401 (Lcom/microsoft/sqlserver/jdbc/SQLServerConnection;II)V
// Stack: 5, Locals: 8
SQLServerStatement(
  com.microsoft.sqlserver.jdbc.SQLServerConnection arg0, int arg1, int arg2) 
throws com.microsoft.sqlserver.jdbc.SQLServerException;

// [...]

34 aload_0 [this]
35 iconst_m1
36 putfield com.microsoft.sqlserver.jdbc.SQLServerStatement.updateCount:int [27]

Now, I will not analyse all possible control-flows, but I'd just say that this is the internal default initialisation value that somehow leaks out to client code. Note, this is also done in other methods:

// Method descriptor #383 ()V
// Stack: 2, Locals: 1
final void resetForReexecute() 
throws com.microsoft.sqlserver.jdbc.SQLServerException;

// [...]

10 aload_0 [this]
11 iconst_m1
12 putfield com.microsoft.sqlserver.jdbc.SQLServerStatement.updateCount:int [27]

// Method descriptor #383 ()V
// Stack: 3, Locals: 3
final void clearLastResult();
0 aload_0 [this]
1 iconst_m1
2 putfield com.microsoft.sqlserver.jdbc.SQLServerStatement.updateCount:int [27]

In other words, you're probably safe interpreting -1 as being the same as 0. If you rely on this result value, maybe stay on the safe side and do your checks as follows:

// No rows affected
if (stmt.executeUpdate() <= 0) {
}
// Rows affected
else {
}

UPDATE: While reading Mark Rotteveel's answer, I tend to agree with him, assuming that -1 is the JDBC-compliant value for "unknown update counts". Even if this isn't documented on the relevant method's Javadoc, it's documented in the JDBC specs, chapter 13.1.2.3 Returning Unknown or Multiple Results. In this very case, it could be said that an IF .. INSERT .. statement will have an "unknown update count", as this statement isn't SQL-standard compliant anyway.

Function overloading in Python: Missing

Now, unless you're trying to write C++ code using Python syntax, what would you need overloading for?

I think it's exactly opposite. Overloading is only necessary to make strongly-typed languages act more like Python. In Python you have keyword argument, and you have *args and **kwargs.

See for example: What is a clean, Pythonic way to have multiple constructors in Python?

How do I loop through a date range?

Here are my 2 cents in 2020.

Enumerable.Range(0, (endDate - startDate).Days + 1)
.ToList()
.Select(a => startDate.AddDays(a));

SQL Server ORDER BY date and nulls last

smalldatetime has range up to June 6, 2079 so you can use

ORDER BY ISNULL(Next_Contact_Date, '2079-06-05T23:59:00')

If no legitimate records will have that date.

If this is not an assumption you fancy relying on a more robust option is sorting on two columns.

ORDER BY CASE WHEN Next_Contact_Date IS NULL THEN 1 ELSE 0 END, Next_Contact_Date

Both of the above suggestions are not able to use an index to avoid a sort however and give similar looking plans.

enter image description here

One other possibility if such an index exists is

SELECT 1 AS Grp, Next_Contact_Date 
FROM T 
WHERE Next_Contact_Date IS NOT NULL
UNION ALL
SELECT 2 AS Grp, Next_Contact_Date 
FROM T 
WHERE Next_Contact_Date IS NULL
ORDER BY Grp, Next_Contact_Date

Plan

How to Get JSON Array Within JSON Object?

Your int length = jsonObj.length(); should be int length = ja_data.length();

Save a subplot in matplotlib

While @Eli is quite correct that there usually isn't much of a need to do it, it is possible. savefig takes a bbox_inches argument that can be used to selectively save only a portion of a figure to an image.

Here's a quick example:

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')

ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')

# Save the full figure...
fig.savefig('full_figure.png')

# Save just the portion _inside_ the second axis's boundaries
extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)

# Pad the saved area by 10% in the x-direction and 20% in the y-direction
fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2))

The full figure: Full Example Figure


Area inside the second subplot: Inside second subplot


Area around the second subplot padded by 10% in the x-direction and 20% in the y-direction: Full second subplot

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

String replace method is not replacing characters

And when I debug this the logic does fall into the sentence.replace.

Yes, and then you discard the return value.

Strings in Java are immutable - when you call replace, it doesn't change the contents of the existing string - it returns a new string with the modifications. So you want:

sentence = sentence.replace("and", " ");

This applies to all the methods in String (substring, toLowerCase etc). None of them change the contents of the string.

Note that you don't really need to do this in a condition - after all, if the sentence doesn't contain "and", it does no harm to perform the replacement:

String sentence = "Define, Measure, Analyze, Design and Verify";
sentence = sentence.replace("and", " ");

How do I set a checkbox in razor view?

The syntax in your last line is correct.

 @Html.CheckBoxFor(x => x.Test, new { @checked = "checked" })

That should definitely work. It is the correct syntax. If you have an existing model and AllowRating is set to true then MVC will add the checked attribute automatically. If AllowRating is set to false MVC won't add the attribute however if desired you can using the above syntax.

CSS center content inside div

You just do CSS changes for parent div

.parent-div { 
        text-align: center;
        display: block;
}

How to generate a Makefile with source in sub-directories using just one makefile

This does the trick:

CC        := g++
LD        := g++

MODULES   := widgets test ui
SRC_DIR   := $(addprefix src/,$(MODULES))
BUILD_DIR := $(addprefix build/,$(MODULES))

SRC       := $(foreach sdir,$(SRC_DIR),$(wildcard $(sdir)/*.cpp))
OBJ       := $(patsubst src/%.cpp,build/%.o,$(SRC))
INCLUDES  := $(addprefix -I,$(SRC_DIR))

vpath %.cpp $(SRC_DIR)

define make-goal
$1/%.o: %.cpp
    $(CC) $(INCLUDES) -c $$< -o $$@
endef

.PHONY: all checkdirs clean

all: checkdirs build/test.exe

build/test.exe: $(OBJ)
    $(LD) $^ -o $@


checkdirs: $(BUILD_DIR)

$(BUILD_DIR):
    @mkdir -p $@

clean:
    @rm -rf $(BUILD_DIR)

$(foreach bdir,$(BUILD_DIR),$(eval $(call make-goal,$(bdir))))

This Makefile assumes you have your include files in the source directories. Also it checks if the build directories exist, and creates them if they do not exist.

The last line is the most important. It creates the implicit rules for each build using the function make-goal, and it is not necessary write them one by one

You can also add automatic dependency generation, using Tromey's way

Can you overload controller methods in ASP.NET MVC?

Yes. I've been able to do this by setting the HttpGet/HttpPost (or equivalent AcceptVerbs attribute) for each controller method to something distinct, i.e., HttpGet or HttpPost, but not both. That way it can tell based on the type of request which method to use.

[HttpGet]
public ActionResult Show()
{
   ...
}

[HttpPost]
public ActionResult Show( string userName )
{
   ...
}

One suggestion I have is that, for a case like this, would be to have a private implementation that both of your public Action methods rely on to avoid duplicating code.

api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

Recursively update Windows 7 until it shows no more updates, using Windows Update check option in Windows 7.

Then download and install Visual C++ Redistributable vc_redist.x64.exe from the Windows website.

Then try to run Apache server.

How to change content on hover

The CSS content property along with ::after and ::before pseudo-elements have been introduced for this.

.item:hover a p.new-label:after{
    content: 'ADD';
}

JSFiddle Demo

printf() prints whole array

Incase of arrays, the base address (i.e. address of the array) is the address of the 1st element in the array. Also the array name acts as a pointer.

Consider a row of houses (each is an element in the array). To identify the row, you only need the 1st house address.You know each house is followed by the next (sequential).Getting the address of the 1st house, will also give you the address of the row.

Incase of string literals(character arrays defined at declaration), they are automatically appended by \0.

printf prints using the format specifier and the address provided. Since, you use %s it prints from the 1st address (incrementing the pointer using arithmetic) until '\0'

Convert JSON string to array of JSON objects in Javascript

Append extra an [ and ] to the beginning and end of the string. This will make it an array. Then use eval() or some safe JSON serializer to serialize the string and make it a real JavaScript datatype.

You should use https://github.com/douglascrockford/JSON-js instead of eval(). eval is only if you're doing some quick debugging/testing.

Android studio: emulator is running but not showing up in Run App "choose a running device"

Wipe the data of your Android virtual Device and then start the emulator. Works for me.

Intellij reformat on file save

This solution worked better for me:

  1. Make a macro (I used Organize Imports, Format Code, Save All)
  2. Assign it a keystroke (I overrode Ctrl+S)

Note: You will have to check the box "Do not show this message again" the first time for the organized imports, but it works as expected after that.

Step-by-step for IntelliJ 10.0:

  1. Code -> "Optimize Imports...", if a dialogue box appears, check the box that says "Do not show this message again.", then click "Run".
  2. Tools -> "Start Macro Recording"
  3. Code -> "Optimize Imports..."
  4. Code -> "Reformat Code..."
  5. File -> "Save all"
  6. Tools -> "Stop Macro Recording"
  7. Name the macro (something like "formatted save")
  8. In File -> Settings -> Keymap, select your macro located at "Main Menu -> Tools -> "formatted save"
  9. Click "Add Keyboard Shortcut", then perform the keystroke you want. If you choose Ctrl+S like me, it will ask you what to do with the previous Ctrl+S shortcut. Remove it. You can always reassign it later if you want.
  10. Enjoy!

For IntelliJ 11, replace

step 2. with: Edit -> Macros -> "Start Macro Recording"
step 6. with: Edit -> Macros -> "Stop Macro Recording"

Everything else remains the same.

IntelliJ 12

8. The Preferences contain the Keymap settings. Use the input field to filter the content, as shown in the screenshot.

Intellij / Preferences / Keymap / Macros

Adding delay between execution of two following lines

[checked 27 Nov 2020 and confirmed to be still accurate with Xcode 12.1]

The most convenient way these days: Xcode provides a code snippet to do this where you just have to enter the delay value and the code you wish to run after the delay.

  1. click on the + button at the top right of Xcode.
  2. search for after
  3. It will return only 1 search result, which is the desired snippet (see screenshot). Double click it and you're good to go.

screenshot illustrating how to get the snippet from within Xcode itself

How can I change the class of an element with jQuery>

<script>
$(document).ready(function(){
      $('button').attr('class','btn btn-primary');
}); </script>

installing apache: no VCRUNTIME140.dll

Check if your OS is Windows 7 Service Pack 1.. use "winver" to verify.

Make sure Service Pack 1 is there after "Build #### : Service Pack 1"

How to run DOS/CMD/Command Prompt commands from VB.NET?

You could try this method:

Public Class MyUtilities
    Shared Sub RunCommandCom(command as String, arguments as String, permanent as Boolean) 
        Dim p as Process = new Process() 
        Dim pi as ProcessStartInfo = new ProcessStartInfo() 
        pi.Arguments = " " + if(permanent = true, "/K" , "/C") + " " + command + " " + arguments 
        pi.FileName = "cmd.exe" 
        p.StartInfo = pi 
        p.Start() 
    End Sub
End Class

call, for example, in this way:

MyUtilities.RunCommandCom("DIR", "/W", true)

EDIT: For the multiple command on one line the key are the & | && and || command connectors

  • A & B → execute command A, then execute command B.
  • A | B → execute command A, and redirect all it's output into the input of command B.
  • A && B → execute command A, evaluate the errorlevel after running Command A, and if the exit code (errorlevel) is 0, only then execute command B.
  • A || B → execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute command B.

How to add a class with React.js?

you can also use pure js to accomplish this like the old ways with jquery

try this if you want a simple way

 document.getElementById("myID").classList.add("show-example");

How to dynamically add and remove form fields in Angular 2

add and remove text input element dynamically any one can use this this will work Type of Contact Balance Fund Equity Fund Allocation Allocation % is required! Remove Add Contact

userForm: FormGroup;
  public contactList: FormArray;
  // returns all form groups under contacts
  get contactFormGroup() {
    return this.userForm.get('funds') as FormArray;
  }
  ngOnInit() {
    this.submitUser();
  }
  constructor(public fb: FormBuilder,private router: Router,private ngZone: NgZone,private userApi: ApiService) { }
  // contact formgroup
  createContact(): FormGroup {
    return this.fb.group({
      fundName: ['', Validators.compose([Validators.required])], // i.e Email, Phone
      allocation: [null, Validators.compose([Validators.required])]
    });
  }


  // triggered to change validation of value field type
  changedFieldType(index) {
    let validators = null;

    validators = Validators.compose([
      Validators.required,
      Validators.pattern(new RegExp('^\\+[0-9]?()[0-9](\\d[0-9]{9})$')) // pattern for validating international phone number
    ]);

    this.getContactsFormGroup(index).controls['allocation'].setValidators(
      validators
    );

    this.getContactsFormGroup(index).controls['allocation'].updateValueAndValidity();
  }

  // get the formgroup under contacts form array
  getContactsFormGroup(index): FormGroup {
    // this.contactList = this.form.get('contacts') as FormArray;
    const formGroup = this.contactList.controls[index] as FormGroup;
    return formGroup;
  }

  submitUser() {
    this.userForm = this.fb.group({
      first_name: ['', [Validators.required]],
      last_name: [''],
      email: ['', [Validators.required]],
      company_name: ['', [Validators.required]],
      license_start_date: ['', [Validators.required]],
      license_end_date: ['', [Validators.required]],
      gender: ['Male'],
      funds: this.fb.array([this.createContact()])
    })
    this.contactList = this.userForm.get('funds') as FormArray;
  }
  addContact() {
    this.contactList.push(this.createContact());
  }
  removeContact(index) {
    this.contactList.removeAt(index);
  }

How do I bottom-align grid elements in bootstrap fluid layout

Well, I didn't like any of those answers, my solution of the same problem was to add this:<div>&nbsp;</div>. So in your scheme it would look like this (more or less), no style changes were necessary in my case:

-row-fluid-------------------------------------
+-span6----------+ +----span6----------+
|                | | +---div---+       |
| content        | | | & nbsp; |       |
| that           | | +---------+       |
| is tall        | | +-----div--------+|   
|                | | |short content   ||
|                | | +----------------+|
+----------------+ +-------------------+
-----------------------------------------------

How do you make Git work with IntelliJ?

Literally, just restarted IntelliJ after it kept showing this "install git" message after I have pressed and installed git, and it disappeared, and git works

phpexcel to download

Use this call

$objWriter->save('php://output');

To output the XLS sheet to the page you are on, just make sure that the page you are on has no other echo's,print's, outputs.

Aborting a stash pop in Git

My use case: just tried popping onto the wrong branch and got conflicts. All I need is to undo the pop but keep it in the stash list so I can pop it out on the correct branch. I did this:

git reset HEAD --hard
git checkout my_correct_branch
git stash pop

Easy.

html5 - canvas element - Multiple layers

No, however, you could layer multiple <canvas> elements on top of each other and accomplish something similar.

<div style="position: relative;">
 <canvas id="layer1" width="100" height="100" 
   style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
 <canvas id="layer2" width="100" height="100" 
   style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>

Draw your first layer on the layer1 canvas, and the second layer on the layer2 canvas. Then when you clearRect on the top layer, whatever's on the lower canvas will show through.

jQuery Call to WebService returns "No Transport" error

i solve it by using dataType='jsonp' at the place of dataType='json'

How to obtain a QuerySet of all rows, with specific fields for each one of them?

In addition to values_list as Daniel mentions you can also use only (or defer for the opposite effect) to get a queryset of objects only having their id and specified fields:

Employees.objects.only('eng_name')

This will run a single query:

SELECT id, eng_name FROM employees

Batch file to delete files older than N days

Might I add a humble contribution to this already valuable thread. I'm finding that other solutions might get rid of the actual error text but are ignoring the %ERRORLEVEL% which signals a fail in my application. AND I legitimately want %ERRORLEVEL% just as long as it isn't the "No files found" error.

Some Examples:

Debugging and eliminating the error specifically:

forfiles /p "[file path...]\IDOC_ARCHIVE" /s /m *.txt /d -1 /c "cmd /c del @path" 2>&1 |  findstr /V /O /C:"ERROR: No files found with the specified search criteria."2>&1 | findstr ERROR&&ECHO found error||echo found success

Using a oneliner to return ERRORLEVEL success or failure:

forfiles /p "[file path...]\IDOC_ARCHIVE" /s /m *.txt /d -1 /c "cmd /c del @path" 2>&1 |  findstr /V /O /C:"ERROR: No files found with the specified search criteria."2>&1 | findstr ERROR&&EXIT /B 1||EXIT /B 0

Using a oneliner to keep the ERRORLEVEL at zero for success within the context of a batchfile in the midst of other code (ver > nul resets the ERRORLEVEL):

forfiles /p "[file path...]\IDOC_ARCHIVE" /s /m *.txt /d -1 /c "cmd /c del @path" 2>&1 |  findstr /V /O /C:"ERROR: No files found with the specified search criteria."2>&1 | findstr ERROR&&ECHO found error||ver > nul

For a SQL Server Agent CmdExec job step I landed on the following. I don't know if it's a bug, but the CmdExec within the step only recognizes the first line of code:

cmd /e:on /c "forfiles /p "C:\SQLADMIN\MAINTREPORTS\SQL2" /s /m *.txt /d -1 /c "cmd /c del @path" 2>&1 |  findstr /V /O /C:"ERROR: No files found with the specified search criteria."2>&1 | findstr ERROR&&EXIT 1||EXIT 0"&exit %errorlevel%

How to save as a new file and keep working on the original one in Vim?

Thanks for the answers. Now I know that there are two ways of "SAVE AS" in Vim.

Assumed that I'm editing hello.txt.

  • :w world.txt will write hello.txt's content to the file world.txt while keeping hello.txt as the opened buffer in vim.
  • :sav world.txt will first write hello.txt's content to the file world.txt, then close buffer hello.txt, finally open world.txt as the current buffer.

Load image from resources area of project in C#

Or you could use this line when dealing with WPF or Silverlight, especially where you have the source string already in the XAML markup:

(ImageSource)new ImageSourceConverter().ConvertFromString(ImagePath);

Where the ImagePath is something like:

string ImagePath  = "/ProjectName;component/Resource/ImageName.png";

Set opacity of background image without affecting child elements

#footer ul li {
  position: relative;
  opacity: 0.99;
}

#footer ul li::before {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: -1;
  background: url(/images/arrow.png) no-repeat 0 50%;
  opacity: 0.5;
}

Hack with opacity .99 (less than 1) creates z-index context so you can not worry about global z-index values. (Try to remove it and see what happens in the next demo where parent wrapper has positive z-index.)
If your element already has z-index, then you don't need this hack.

Demo of this technique.

Multiple submit buttons on HTML form – designate one button as default

bobince's solution has the downside of creating a button which can be Tab-d over, but otherwise unusable. This can create confusion for keyboard users.

A different solution is to use the little-known form attribute:

<form>
    <input name="data" value="Form data here">
    <input type="submit" name="do-secondary-action" form="form2" value="Do secondary action">
    <input type="submit" name="submit" value="Submit">
</form>

<form id="form2"></form>

This is standard HTML, however unfortunately not supported in Internet Explorer.

How can I test a Windows DLL file to determine if it is 32 bit or 64 bit?

Gory details

A DLL uses the PE executable format, and it's not too tricky to read that information out of the file.

See this MSDN article on the PE File Format for an overview. You need to read the MS-DOS header, then read the IMAGE_NT_HEADERS structure. This contains the IMAGE_FILE_HEADER structure which contains the info you need in the Machine member which contains one of the following values

  • IMAGE_FILE_MACHINE_I386 (0x014c)
  • IMAGE_FILE_MACHINE_IA64 (0x0200)
  • IMAGE_FILE_MACHINE_AMD64 (0x8664)

This information should be at a fixed offset in the file, but I'd still recommend traversing the file and checking the signature of the MS-DOS header and the IMAGE_NT_HEADERS to be sure you cope with any future changes.

Use ImageHelp to read the headers...

You can also use the ImageHelp API to do this - load the DLL with LoadImage and you'll get a LOADED_IMAGE structure which will contain a pointer to an IMAGE_NT_HEADERS structure. Deallocate the LOADED_IMAGE with ImageUnload.

...or adapt this rough Perl script

Here's rough Perl script which gets the job done. It checks the file has a DOS header, then reads the PE offset from the IMAGE_DOS_HEADER 60 bytes into the file.

It then seeks to the start of the PE part, reads the signature and checks it, and then extracts the value we're interested in.

#!/usr/bin/perl
#
# usage: petype <exefile>
#
$exe = $ARGV[0];

open(EXE, $exe) or die "can't open $exe: $!";
binmode(EXE);
if (read(EXE, $doshdr, 64)) {

   ($magic,$skip,$offset)=unpack('a2a58l', $doshdr);
   die("Not an executable") if ($magic ne 'MZ');

   seek(EXE,$offset,SEEK_SET);
   if (read(EXE, $pehdr, 6)){
       ($sig,$skip,$machine)=unpack('a2a2v', $pehdr);
       die("No a PE Executable") if ($sig ne 'PE');

       if ($machine == 0x014c){
            print "i386\n";
       }
       elsif ($machine == 0x0200){
            print "IA64\n";
       }
       elsif ($machine == 0x8664){
            print "AMD64\n";
       }
       else{
            printf("Unknown machine type 0x%lx\n", $machine);
       }
   }
}

close(EXE);

HTML/CSS font color vs span style

Use style. The font tag is deprecated (W3C Wiki).

Explaining the 'find -mtime' command

+1 means 2 days ago. It's rounded.

Waiting on a list of Future

Use a CompletableFuture in Java 8

    // Kick of multiple, asynchronous lookups
    CompletableFuture<User> page1 = gitHubLookupService.findUser("Test1");
    CompletableFuture<User> page2 = gitHubLookupService.findUser("Test2");
    CompletableFuture<User> page3 = gitHubLookupService.findUser("Test3");

    // Wait until they are all done
    CompletableFuture.allOf(page1,page2,page3).join();

    logger.info("--> " + page1.get());

Custom exception type

Yes. You can throw anything you want: integers, strings, objects, whatever. If you want to throw an object, then simply create a new object, just as you would create one under other circumstances, and then throw it. Mozilla's Javascript reference has several examples.

How to add RSA key to authorized_keys file?

>ssh user@serverip -p portnumber 
>sudo bash (if user does not have bash shell else skip this line)
>cd /home/user/.ssh
>echo ssh_rsa...this is the key >> authorized_keys

subsetting a Python DataFrame

I'll assume that Time and Product are columns in a DataFrame, df is an instance of DataFrame, and that other variables are scalar values:

For now, you'll have to reference the DataFrame instance:

k1 = df.loc[(df.Product == p_id) & (df.Time >= start_time) & (df.Time < end_time), ['Time', 'Product']]

The parentheses are also necessary, because of the precedence of the & operator vs. the comparison operators. The & operator is actually an overloaded bitwise operator which has the same precedence as arithmetic operators which in turn have a higher precedence than comparison operators.

In pandas 0.13 a new experimental DataFrame.query() method will be available. It's extremely similar to subset modulo the select argument:

With query() you'd do it like this:

df[['Time', 'Product']].query('Product == p_id and Month < mn and Year == yr')

Here's a simple example:

In [9]: df = DataFrame({'gender': np.random.choice(['m', 'f'], size=10), 'price': poisson(100, size=10)})

In [10]: df
Out[10]:
  gender  price
0      m     89
1      f    123
2      f    100
3      m    104
4      m     98
5      m    103
6      f    100
7      f    109
8      f     95
9      m     87

In [11]: df.query('gender == "m" and price < 100')
Out[11]:
  gender  price
0      m     89
4      m     98
9      m     87

The final query that you're interested will even be able to take advantage of chained comparisons, like this:

k1 = df[['Time', 'Product']].query('Product == p_id and start_time <= Time < end_time')

How do I create a HTTP Client Request with a cookie?

This answer is deprecated, please see @ankitjaininfo's answer below for a more modern solution


Here's how I think you make a POST request with data and a cookie using just the node http library. This example is posting JSON, set your content-type and content-length accordingly if you post different data.

// NB:- node's http client API has changed since this was written
// this code is for 0.4.x
// for 0.6.5+ see http://nodejs.org/docs/v0.6.5/api/http.html#http.request

var http = require('http');

var data = JSON.stringify({ 'important': 'data' });
var cookie = 'something=anything'

var client = http.createClient(80, 'www.example.com');

var headers = {
    'Host': 'www.example.com',
    'Cookie': cookie,
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(data,'utf8')
};

var request = client.request('POST', '/', headers);

// listening to the response is optional, I suppose
request.on('response', function(response) {
  response.on('data', function(chunk) {
    // do what you do
  });
  response.on('end', function() {
    // do what you do
  });
});
// you'd also want to listen for errors in production

request.write(data);

request.end();

What you send in the Cookie value should really depend on what you received from the server. Wikipedia's write-up of this stuff is pretty good: http://en.wikipedia.org/wiki/HTTP_cookie#Cookie_attributes

How do I select the parent form based on which submit button is clicked?

Eileen: No, it is not var nameVal = form.inputname.val();. It should be either...

in jQuery:

// you can use IDs (easier)

var nameVal =  $(form).find('#id').val();

// or use the [name=Fieldname] to search for the field

var nameVal =  $(form).find('[name=Fieldname]').val();

Or in JavaScript:

var nameVal = this.form.FieldName.value;

Or a combination:

var nameVal = $(this.form.FieldName).val();

With jQuery, you could even loop through all of the inputs in the form:

$(form).find('input, select, textarea').each(function(){

  var name = this.name;
  // OR
  var name = $(this).attr('name');

  var value = this.value;
  // OR
  var value = $(this).val();
  ....
  });

dpi value of default "large", "medium" and "small" text views android

To put it in another way, can we replicate the appearance of these text views without using the android:textAppearance attribute?

Like biegleux already said:

  • small represents 14sp
  • medium represents 18sp
  • large represents 22sp

If you want to use the small, medium or large value on any text in your Android app, you can just create a dimens.xml file in your values folder and define the text size there with the following 3 lines:

<dimen name="text_size_small">14sp</dimen>
<dimen name="text_size_medium">18sp</dimen>
<dimen name="text_size_large">22sp</dimen>

Here is an example for a TextView with large text from the dimens.xml file:

<TextView
  android:id="@+id/hello_world"
  android:text="hello world"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:textSize="@dimen/text_size_large"/>

MySQL - ignore insert error: duplicate entry

Try creating a duplicate table, preferably a temporary table, without the unique constraint and do your bulk load into that table. Then select only the unique (DISTINCT) items from the temporary table and insert into the target table.

HTML CSS Button Positioning

[type=submit]{
    margin-left: 121px;
    margin-top: 19px;
    width: 84px;
    height: 40px;   
    font-size:14px;
    font-weight:700;
}

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Use the IP instead:

DROP USER 'root'@'127.0.0.1'; GRANT ALL PRIVILEGES ON . TO 'root'@'%';

For more possibilities, see this link.

To create the root user, seeing as MySQL is local & all, execute the following from the command line (Start > Run > "cmd" without quotes):

mysqladmin -u root password 'mynewpassword'

Documentation, and Lost root access in MySQL.

DBCC CHECKIDENT Sets Identity to 0

I did this as an experiment to reset the value to 0 as I want my first identity column to be 0 and it's working.

dbcc CHECKIDENT(MOVIE,RESEED,0)
dbcc CHECKIDENT(MOVIE,RESEED,-1)
DBCC CHECKIDENT(MOVIE,NORESEED)

Regex: ignore case sensitivity

Depends on implementation but I would use

(?i)G[a-b].

VARIATIONS:

(?i) case-insensitive mode ON    
(?-i) case-insensitive mode OFF

Modern regex flavors allow you to apply modifiers to only part of the regular expression. If you insert the modifier (?im) in the middle of the regex then the modifier only applies to the part of the regex to the right of the modifier. With these flavors, you can turn off modes by preceding them with a minus sign (?-i).

Description is from the page: https://www.regular-expressions.info/modifiers.html

RE error: illegal byte sequence on Mac OS X

Add the following lines to your ~/.bash_profile or ~/.zshrc file(s).

export LC_CTYPE=C 
export LANG=C

How do I add an existing directory tree to a project in Visual Studio?

As far as I can tell, the only way to do this in VS2010 is akin to the drag and drop method. Right click the solution to which you want to add a project. The application menu will have an add ... item. Opening that, you find that one of the options is to add an existing project to the solution.

In the dialog box that opens, navigate to the folder containing the project file for the solution and select it. VS will, as part of importing that project file, also import the entire directory and, I assume any subordinate directories which are part of that project.

As this does require an existing project file, it won't be impossible to import a directory tree until that tree has been converted to a project.

How to remove a package from Laravel using composer?

There are quite a few steps here:

  1. Go to composer.json and look for the package and how it is written over there.
  • for example

{ "require": { "twig/twig": "^3.0" } }

I wish to remove twig 3.0

  1. Now open cmd and run composer remove vendor/your_package_name as composer remove twig/twig this will remove the package.

  2. As a final step run composer update this will surely give you a massage of nothing to install or update but this is important in case your packages have inter-dependencies.

How do I encode/decode HTML entities in Ruby?

<% str="<h1> Test </h1>" %>

result: &lt; h1 &gt; Test &lt; /h1 &gt;

<%= CGI.unescapeHTML(str).html_safe %>

How to downgrade php from 5.5 to 5.3

It is possible! Yes

In many cases, you might want to use XAMPP with a different PHP version than the one that comes preinstalled. You might do this to get the benefits of a newer version of PHP, or to reproduce bugs using an earlier version of PHP.

To use a different version of PHP with XAMPP, follow these steps:

  1. Download a binary build of the PHP version that you wish to use from the PHP website, and extract the contents of the compressed archive file to your XAMPP installation directory (usually, C:\xampp). Ensure that you give it a different directory name to avoid overwriting the existing PHP version. For example, in this tutorial, we’ll call the new directory C:\xampp\php5-6-0. NOTE : Ensure that the PHP build you download matches the Apache build (VC9 or VC11) in your XAMPP platform.

  2. Within the new directory, rename the php.ini-development file to php.ini. If you prefer to use production settings, you could instead rename the php.ini-production file to php.ini.

  3. Edit the httpd-xampp.conf file in the apache\conf\extra\ subdirectory of your XAMPP installation directory. Within this file, search for all instances of the old PHP directory path and replace them with the path to the new PHP directory created in Step 1. In particular, be sure to change the lines

    LoadFile "/xampp/php/php5ts.dll"
    LoadFile "/xampp/php/libpq.dll"
    LoadModule php5_module "/xampp/php/php5apache2_4.dll"

to

    LoadFile "/xampp/php5-6-0/php5ts.dll"
    LoadFile "/xampp/php5-6-0/libpq.dll"
    LoadModule php5_module "/xampp/php5-6-0/php5apache2_4.dll"

NOTE : Remember to adjust the file and directory paths above to reflect valid paths on your system.

  1. Restart your Apache server through the XAMPP control panel for your changes to take effect. The new version of PHP should now be active. To verify this, browse to the URL http://localhost/xampp/phpinfo.php, which displays the output of the phpinfo() command, and check the version number at the top of the page.

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Your cells object is not fully qualified. You need to add a DOT before the cells object. For example

With Worksheets("Cable Cards")
    .Range(.Cells(RangeStartRow, RangeStartColumn), _
           .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

Similarly, fully qualify all your Cells object.

How do ACID and database transactions work?

ACID is a set of properties that you would like to apply when modifying a database.

  • Atomicity
  • Consistency
  • Isolation
  • Durability

A transaction is a set of related changes which is used to achieve some of the ACID properties. Transactions are tools to achieve the ACID properties.

Atomicity means that you can guarantee that all of a transaction happens, or none of it does; you can do complex operations as one single unit, all or nothing, and a crash, power failure, error, or anything else won't allow you to be in a state in which only some of the related changes have happened.

Consistency means that you guarantee that your data will be consistent; none of the constraints you have on related data will ever be violated.

Isolation means that one transaction cannot read data from another transaction that is not yet completed. If two transactions are executing concurrently, each one will see the world as if they were executing sequentially, and if one needs to read data that is written by another, it will have to wait until the other is finished.

Durability means that once a transaction is complete, it is guaranteed that all of the changes have been recorded to a durable medium (such as a hard disk), and the fact that the transaction has been completed is likewise recorded.

So, transactions are a mechanism for guaranteeing these properties; they are a way of grouping related actions together such that as a whole, a group of operations can be atomic, produce consistent results, be isolated from other operations, and be durably recorded.

Does MySQL foreign_key_checks affect the entire database?

I had the same error when I tried to migrate Drupal database to a new local apache server(I am using XAMPP on Windows machine). Actually I don't know the meaning of this error, but after trying steps below, I imported the database without errors. Hope this could help:

Changing php.ini at C:\xampp\php\php.ini

max_execution_time = 600
max_input_time = 600
memory_limit = 1024M
post_max_size = 1024M

Changing my.ini at C:\xampp\mysql\bin\my.ini

max_allowed_packet = 1024M

Hide div if screen is smaller than a certain width

I have the almost the same situation as yours; that if the screen width is less than the my specified width it should hide the div. This is the jquery code I used that worked for me.

$(window).resize(function() {

  if ($(this).width() < 1024) {

    $('.divIWantedToHide').hide();

  } else {

    $('.divIWantedToHide').show();

    }

});

Writing files in Node.js

You may write to a file using fs (file system) module.

Here is an example of how you may do it:

const fs = require('fs');

const writeToFile = (fileName, callback) => {
  fs.open(fileName, 'wx', (error, fileDescriptor) => {
    if (!error && fileDescriptor) {
      // Do something with the file here ...
      fs.writeFile(fileDescriptor, newData, (error) => {
        if (!error) {
          fs.close(fileDescriptor, (error) => {
            if (!error) {
              callback(false);
            } else {
              callback('Error closing the file');
            }
          });
        } else {
          callback('Error writing to new file');
        }
      });
    } else {
      callback('Could not create new file, it may already exists');
    }
  });
};

You might also want to get rid of this callback-inside-callback code structure by useing Promises and async/await statements. This will make asynchronous code structure much more flat. For doing that there is a handy util.promisify(original) function might be utilized. It allows us to switch from callbacks to promises. Take a look at the example with fs functions below:

// Dependencies.
const util = require('util');
const fs = require('fs');

// Promisify "error-back" functions.
const fsOpen = util.promisify(fs.open);
const fsWrite = util.promisify(fs.writeFile);
const fsClose = util.promisify(fs.close);

// Now we may create 'async' function with 'await's.
async function doSomethingWithFile(fileName) {
  const fileDescriptor = await fsOpen(fileName, 'wx');

  // Do something with the file here...

  await fsWrite(fileDescriptor, newData);
  await fsClose(fileDescriptor);
}

How do I make a semi transparent background?

If you want to make transparent background is gray, pls try:

   .transparent{
       background:rgba(1,1,1,0.5);
   }

Beginner Python Practice?

You may be interested in Python interactive tutorial for begginers and advance users , it has many available practices together with interactive interface + advance development tricks for advance users.

How do I get the HTTP status code with jQuery?

Use the error callback.

For example:

jQuery.ajax({'url': '/this_is_not_found', data: {}, error: function(xhr, status) {
    alert(xhr.status); }
});

Will alert 404

How do you get/set media volume (not ringtone volume) in Android?

private AudioManager audio;

Inside onCreate:

audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

Override onKeyDown:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
    case KeyEvent.KEYCODE_VOLUME_UP:
        audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
        return true;
    default:
        return false;
    }
}

How do I generate random numbers in Dart?

An alternative solution could be using the following code DRandom. This class should be used with a seed. It provides a familiar interface to what you would expect in .NET, it was ported from mono's Random.cs. This code may not be cryptography safe and has not been statistically tested.

jQuery animate backgroundColor

If you wan't to animate your background using only core jQuery functionality, try this:

jQuery(".usercontent").mouseover(function() {
      jQuery(".usercontent").animate({backgroundColor:'red'}, 'fast', 'linear', function() {
            jQuery(this).animate({
                backgroundColor: 'white'
            }, 'normal', 'linear', function() {
                jQuery(this).css({'background':'none', backgroundColor : ''});
            });
        });

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

"The public type <<classname>> must be defined in its own file" error in Eclipse

You can't use 2 public class instances, you need to use one. Try using class (name) instead of public class (name)

How to check for the type of a template parameter?

In C++17, we can use variants.

To use std::variant, you need to include the header:

#include <variant>

After that, you may add std::variant in your code like this:

using Type = std::variant<Animal, Person>;

template <class T>
void foo(Type type) {
    if (std::is_same_v<type, Animal>) {
        // Do stuff...
    } else {
        // Do stuff...
    }
}

SELECT FOR UPDATE with SQL Server

Question - is this case proven to be the result of lock escalation (i.e. if you trace with profiler for lock escalation events, is that definitely what is happening to cause the blocking)? If so, there is a full explanation and a (rather extreme) workaround by enabling a trace flag at the instance level to prevent lock escalation. See http://support.microsoft.com/kb/323630 trace flag 1211

But, that will likely have unintended side effects.

If you are deliberately locking a row and keeping it locked for an extended period, then using the internal locking mechanism for transactions isn't the best method (in SQL Server at least). All the optimization in SQL Server is geared toward short transactions - get in, make an update, get out. That's the reason for lock escalation in the first place.

So if the intent is to "check out" a row for a prolonged period, instead of transactional locking it's best to use a column with values and a plain ol' update statement to flag the rows as locked or not.

Invariant Violation: Objects are not valid as a React child

Found: object with keys

Which means you passing something is a key-value. So you need to modify your handler:

from
onItemClick(e, item) {
   this.setState({
     lang: item,
   });
}
to
onItemClick({e, item}) {
  this.setState({
    lang: item,
  });
}

You missed out the braces ({}).

SVN Repository on Google Drive or DropBox

I would try fossil scm and the Chisel hosting service

simple, self contained and easily interchangeable with git should you desire in future

How do I set specific environment variables when debugging in Visual Studio?

In Visual Studio 2008 and Visual Studio 2005 at least, you can specify changes to environment variables in the project settings.

Open your project. Go to Project -> Properties... Under Configuration Properties -> Debugging, edit the 'Environment' value to set environment variables.

For example, if you want to add the directory "c:\foo\bin" to the path when debugging your application, set the 'Environment' value to "PATH=%PATH%;c:\foo\bin".

Here's a screenshot of the settings dialog

How to turn on front flash light programmatically in Android?

I Got AutoFlash light with below simple Three Steps.

  • I just added Camera and Flash Permission in Manifest.xml file
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />

<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-feature android:name="android.hardware.camera.flash" android:required="false" />
  • In your Camera Code do this way.

    //Open Camera
    Camera  mCamera = Camera.open(); 
    
    //Get Camera Params for customisation
    Camera.Parameters parameters = mCamera.getParameters();
    
    //Check Whether device supports AutoFlash, If you YES then set AutoFlash
    List<String> flashModes = parameters.getSupportedFlashModes();
    if (flashModes.contains(android.hardware.Camera.Parameters.FLASH_MODE_AUTO))
    {
         parameters.setFlashMode(Parameters.FLASH_MODE_AUTO);
    }
    mCamera.setParameters(parameters);
    mCamera.startPreview();
    
  • Build + Run —> Now Go to Dim light area and Snap photo, you should get auto flash light if device supports.

filter: progid:DXImageTransform.Microsoft.gradient is not working in ie7

In testing IE7/8/9 I was getting an ActiveX warning trying to use this code snippet:

filter:progid:DXImageTransform.Microsoft.gradient

After removing this the warning went away. I know this isn't an answer, but I thought it was worthwhile to note.

How to turn a string formula into a "real" formula

UPDATE This used to work (in 2007, I believe), but does not in Excel 2013.

EXCEL 2013:

This isn't quite the same, but if it's possible to put 0.4 in one cell (B1, say), and the text value A1 in another cell (C1, say), in cell D1, you can use =B1*INDIRECT(C1), which results in the calculation of 0.4 * A1's value.

So, if A1 = 10, you'd get 0.4*10 = 4 in cell D1. I'll update again if I can find a better 2013 solution, and sorry the Microsoft destroyed the original functionality of INDIRECT!

EXCEL 2007 version:

For a non-VBA solution, use the INDIRECT formula. It takes a string as an argument and converts it to a cell reference.

For example, =0.4*INDIRECT("A1") will return the value of 0.4 * the value that's in cell A1 of that worksheet.

If cell A1 was, say, 10, then =0.4*INDIRECT("A1") would return 4.

How to find out which processes are using swap space in Linux?

I did notice this thread is rather old, but if you happen to stumble upon it, as I just did, another answer is: use smem.

Here is a link which tells you both how to install it and how to use it:

http://www.cyberciti.biz/faq/linux-which-process-is-using-swap/

How to do 3 table JOIN in UPDATE query?

Below is the Update query which includes JOIN & WHERE both. Same way we can use multiple join/where clause, Hope it will help you :-

UPDATE opportunities_cstm oc JOIN opportunities o ON oc.id_c = o.id
 SET oc.forecast_stage_c = 'APX'
 WHERE o.deleted = 0
   AND o.sales_stage IN('ABC','PQR','XYZ')

Docker: Copying files from Docker container to host

sudo docker cp <running_container_id>:<full_file_path_in_container> <path_on_local_machine>

Example :

sudo docker cp d8a17dfc455f:/tests/reports /home/acbcb/Documents/abc

How do I write a for loop in bash

I use variations of this all the time to process files...

for files in *.log; do echo "Do stuff with: $files"; echo "Do more stuff with: $files"; done;

If processing lists of files is what you're interested in, look into the -execdir option for files.

How do I convert hh:mm:ss.000 to milliseconds in Excel?

Use

=LEFT(B2, 2)*3600000 + MID(B2,4,2) * 60000 + MID(B2,7,2)*1000 + RIGHT(B2,3)

_tkinter.TclError: no display name and no $DISPLAY environment variable

To add up on the answer, I used this at the beginning of the needed script. So it runs smoothly on different environments.

import os
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
    print('no display found. Using non-interactive Agg backend')
    mpl.use('Agg')
import matplotlib.pyplot as plt

Because I didn't want it to be alsways using the 'Agg' backend, only when it would go through Travis CI for example.

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:

SELECT t0.foo, t1.bar
  FROM FIRST_TABLE t0
 RIGHT OUTER JOIN SECOND_TABLE t1;

Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

Set field value with reflection

You can try this:

//Your class instance
Publication publication = new Publication();

//Get class with full path(with package name)
Class<?> c = Class.forName("com.example.publication.models.Publication");

//Get method
Method  method = c.getDeclaredMethod ("setTitle", String.class);

//set value
method.invoke (publication,  "Value to want to set here...");

How do you clear a stringstream variable?

my 2 cents:

this seemed to work for me in xcode and dev-c++, I had a program in the form of a menu that if executed iteratively as per the request of a user will fill up a stringstream variable which would work ok the first time the code would run but would not clear the stringstream the next time the user will run the same code. but the two lines of code below finally cleared up the stringstream variable everytime before filling up the string variable. (2 hours of trial and error and google searches), btw, using each line on their own would not do the trick.

//clear the stringstream variable

sstm.str("");
sstm.clear();

//fill up the streamstream variable
sstm << "crap" << "morecrap";

Proxy with urllib2

In addition set the proxy for the command line session Open a command line where you might want to run your script

netsh winhttp set proxy YourProxySERVER:yourProxyPORT

run your script in that terminal.

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

I was unable to access to S3 because

  • first I configured key access on the instance (it was impossible to attach role after the launch then)
  • forgot about it for a few months
  • attached role to instance
  • tried to access. The configured key had higher priority than role, and access was denied because the user wasn't granted with necessary S3 permissions.

Solution: rm -rf .aws/credentials, then aws uses role.

Filter Excel pivot table using VBA

Field.CurrentPage only works for Filter fields (also called page fields).
If you want to filter a row/column field, you have to cycle through the individual items, like so:

Sub FilterPivotField(Field As PivotField, Value)
    Application.ScreenUpdating = False
    With Field
        If .Orientation = xlPageField Then
            .CurrentPage = Value
        ElseIf .Orientation = xlRowField Or .Orientation = xlColumnField Then
            Dim i As Long
            On Error Resume Next ' Needed to avoid getting errors when manipulating PivotItems that were deleted from the data source.
            ' Set first item to Visible to avoid getting no visible items while working
            .PivotItems(1).Visible = True
            For i = 2 To Field.PivotItems.Count
                If .PivotItems(i).Name = Value Then _
                    .PivotItems(i).Visible = True Else _
                    .PivotItems(i).Visible = False
            Next i
            If .PivotItems(1).Name = Value Then _
                .PivotItems(1).Visible = True Else _
                .PivotItems(1).Visible = False
        End If
    End With
    Application.ScreenUpdating = True
End Sub

Then, you would just call:

FilterPivotField ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode"), "K123223"

Naturally, this gets slower the more there are individual different items in the field. You can also use SourceName instead of Name if that suits your needs better.

Https to http redirect using htaccess

RewriteCond %{HTTP:X-Forwarded-Proto} =https

How do I truly reset every setting in Visual Studio 2012?

Visual Studio has multiple flags to reset various settings:

  • /ResetUserData - (AFAICT) Removes all user settings and makes you set them again. This will get you the initial prompt for settings again, clear your recent project history, etc.
  • /ResetSettings - Restores the IDE's default settings, optionally resets to the specified VSSettings file.
  • /ResetSkipPkgs - Clears all SkipLoading tags added to VSPackages.
  • /ResetAddin - Removes commands and command UI associated with the specified Add-in.

The last three show up when running devenv.exe /?. The first one seems to be undocumented/unsupported/the big hammer. From here:

Disclaimer: you will lose all your environment settings and customizations if you use this switch. It is for this reason that this switch is not officially supported and Microsoft does not advertise this switch to the public (you won't see this switch if you type devenv.exe /? in the command prompt). You should only use this switch as the last resort if you are experiencing an environment problem, and make sure you back up your environment settings by exporting them before using this switch.

How can I make my custom objects Parcelable?

Android parcable has some unique things. Those are given bellow:

  1. You have to read Parcel as the same order where you put data on parcel.
  2. Parcel will empty after read from parcel. That is if you have 3 data on your parcel. Then after read 3 times parcel will be empty.

Example: To make a class Parceble it must be implement Parceble. Percable has 2 method:

int describeContents();
void writeToParcel(Parcel var1, int var2);

Suppose you have a Person class and it has 3 field, firstName,lastName and age. After implementing Parceble interface. this interface is given bellow:

import android.os.Parcel;
import android.os.Parcelable;
public class Person implements Parcelable{
    private String firstName;
    private String lastName;
    private int age;

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(firstName);
        parcel.writeString(lastName);
        parcel.writeInt(age);
    }

}

Here writeToParcel method we are writing/adding data on Parcel in an order. After this we have to add bellow code for reading data from parcel:

protected Person(Parcel in) {
        firstName = in.readString();
        lastName = in.readString();
        age = in.readInt();
    }

    public static final Creator<Person> CREATOR = new Creator<Person>() {
        @Override
        public Person createFromParcel(Parcel in) {
            return new Person(in);
        }

        @Override
        public Person[] newArray(int size) {
            return new Person[size];
        }
    };

Here, Person class is taking a parcel and getting data in same an order during writing.

Now during intent getExtra and putExtra code is given bellow:

Put in Extra:

Person person=new Person();
                person.setFirstName("First");
                person.setLastName("Name");
                person.setAge(30);

                Intent intent = new Intent(getApplicationContext(), SECOND_ACTIVITY.class);
                intent.putExtra()
                startActivity(intent); 

Get Extra:

Person person=getIntent().getParcelableExtra("person");

Full Person class is given bellow:

import android.os.Parcel;
import android.os.Parcelable;

public class Person implements Parcelable{
    private String firstName;
    private String lastName;
    private int age;



    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(firstName);
        parcel.writeString(lastName);
        parcel.writeInt(age);
    }

    protected Person(Parcel in) {
        firstName = in.readString();
        lastName = in.readString();
        age = in.readInt();
    }

    public static final Creator<Person> CREATOR = new Creator<Person>() {
        @Override
        public Person createFromParcel(Parcel in) {
            return new Person(in);
        }

        @Override
        public Person[] newArray(int size) {
            return new Person[size];
        }
    };

}

Hope this will help you 
Thanks :)

How to change a PG column to NULLABLE TRUE?

From the fine manual:

ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;

There's no need to specify the type when you're just changing the nullability.

Unable to copy ~/.ssh/id_rsa.pub

Have read the documentation you've linked. That's totally silly! xclip is just a clipboard. You'll find other ways to copy paste the key... (I'm sure)


If you aren't working from inside a graphical X session you need to pass the $DISPLAY environment var to the command. Run it like this:

DISPLAY=:0 xclip -sel clip < ~/.ssh/id_rsa.pub

Of course :0 depends on the display you are using. If you have a typical desktop machine it is likely that it is :0

Update multiple rows using select statement

You can use alias to improve the query:

UPDATE t1
   SET t1.Value = t2.Value
  FROM table1 AS t1
         INNER JOIN 
       table2 AS t2
         ON t1.ID = t2.ID

How to resize Twitter Bootstrap modal dynamically based on the content

I simply override the css:

.modal-dialog {
    max-width: 1000px;
}

Center-align a HTML table

Try this -

<table align="center" style="margin: 0px auto;"></table>

IN Clause with NULL or IS NULL

SELECT *
FROM tbl_name
WHERE coalesce(id_field,'unik_null_value') 
IN ('value1', 'value2', 'value3', 'unik_null_value')

So that you eliminate the null from the check. Given a null value in id_field, the coalesce function would instead of null return 'unik_null_value', and by adding 'unik_null_value to the IN-list, the query would return posts where id_field is value1-3 or null.

How can I extract substrings from a string in Perl?

Long time no Perl

while(<STDIN>) {
    next unless /:\s*(\S+)\s+\(([^\)]+)\)\s*(\*?)/;
    print "|$1|$2|$3|\n";
}

How could I put a border on my grid control in WPF?

I think your problem is that the margin should be specified in the border tag and not in the grid.

Change <br> height using CSS

As the 'margin' doesn't work in Chrome, that's why I used 'border' instead.

br {
  display: block;
  content: "";
  border-bottom: 10px solid transparent; // Works in Chrome/Safari
}
@-moz-document url-prefix() {
  br {
    margin-bottom: 10px; // As 'border-bottom' doesn't work in firefox and 'margin-bottom' doesn't work in Chrome/Safari.
  }
}

Most efficient way to remove special characters from string

I'm not sure it is the most efficient way, but It works for me

 Public Function RemoverTildes(stIn As String) As String
    Dim stFormD As String = stIn.Normalize(NormalizationForm.FormD)
    Dim sb As New StringBuilder()

    For ich As Integer = 0 To stFormD.Length - 1
        Dim uc As UnicodeCategory = CharUnicodeInfo.GetUnicodeCategory(stFormD(ich))
        If uc <> UnicodeCategory.NonSpacingMark Then
            sb.Append(stFormD(ich))
        End If
    Next
    Return (sb.ToString().Normalize(NormalizationForm.FormC))
End Function

Java 8: Lambda-Streams, Filter by Method with Exception

This UtilException helper class lets you use any checked exceptions in Java streams, like this:

Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
      .map(rethrowFunction(Class::forName))
      .collect(Collectors.toList());

Note Class::forName throws ClassNotFoundException, which is checked. The stream itself also throws ClassNotFoundException, and NOT some wrapping unchecked exception.

public final class UtilException {

@FunctionalInterface
public interface Consumer_WithExceptions<T, E extends Exception> {
    void accept(T t) throws E;
    }

@FunctionalInterface
public interface BiConsumer_WithExceptions<T, U, E extends Exception> {
    void accept(T t, U u) throws E;
    }

@FunctionalInterface
public interface Function_WithExceptions<T, R, E extends Exception> {
    R apply(T t) throws E;
    }

@FunctionalInterface
public interface Supplier_WithExceptions<T, E extends Exception> {
    T get() throws E;
    }

@FunctionalInterface
public interface Runnable_WithExceptions<E extends Exception> {
    void run() throws E;
    }

/** .forEach(rethrowConsumer(name -> System.out.println(Class.forName(name)))); or .forEach(rethrowConsumer(ClassNameUtil::println)); */
public static <T, E extends Exception> Consumer<T> rethrowConsumer(Consumer_WithExceptions<T, E> consumer) throws E {
    return t -> {
        try { consumer.accept(t); }
        catch (Exception exception) { throwAsUnchecked(exception); }
        };
    }

public static <T, U, E extends Exception> BiConsumer<T, U> rethrowBiConsumer(BiConsumer_WithExceptions<T, U, E> biConsumer) throws E {
    return (t, u) -> {
        try { biConsumer.accept(t, u); }
        catch (Exception exception) { throwAsUnchecked(exception); }
        };
    }

/** .map(rethrowFunction(name -> Class.forName(name))) or .map(rethrowFunction(Class::forName)) */
public static <T, R, E extends Exception> Function<T, R> rethrowFunction(Function_WithExceptions<T, R, E> function) throws E {
    return t -> {
        try { return function.apply(t); }
        catch (Exception exception) { throwAsUnchecked(exception); return null; }
        };
    }

/** rethrowSupplier(() -> new StringJoiner(new String(new byte[]{77, 97, 114, 107}, "UTF-8"))), */
public static <T, E extends Exception> Supplier<T> rethrowSupplier(Supplier_WithExceptions<T, E> function) throws E {
    return () -> {
        try { return function.get(); }
        catch (Exception exception) { throwAsUnchecked(exception); return null; }
        };
    }

/** uncheck(() -> Class.forName("xxx")); */
public static void uncheck(Runnable_WithExceptions t)
    {
    try { t.run(); }
    catch (Exception exception) { throwAsUnchecked(exception); }
    }

/** uncheck(() -> Class.forName("xxx")); */
public static <R, E extends Exception> R uncheck(Supplier_WithExceptions<R, E> supplier)
    {
    try { return supplier.get(); }
    catch (Exception exception) { throwAsUnchecked(exception); return null; }
    }

/** uncheck(Class::forName, "xxx"); */
public static <T, R, E extends Exception> R uncheck(Function_WithExceptions<T, R, E> function, T t) {
    try { return function.apply(t); }
    catch (Exception exception) { throwAsUnchecked(exception); return null; }
    }

@SuppressWarnings ("unchecked")
private static <E extends Throwable> void throwAsUnchecked(Exception exception) throws E { throw (E)exception; }

}

Many other examples on how to use it (after statically importing UtilException):

@Test
public void test_Consumer_with_checked_exceptions() throws IllegalAccessException {
    Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
          .forEach(rethrowConsumer(className -> System.out.println(Class.forName(className))));

    Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
          .forEach(rethrowConsumer(System.out::println));
    }

@Test
public void test_Function_with_checked_exceptions() throws ClassNotFoundException {
    List<Class> classes1
          = Stream.of("Object", "Integer", "String")
                  .map(rethrowFunction(className -> Class.forName("java.lang." + className)))
                  .collect(Collectors.toList());

    List<Class> classes2
          = Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
                  .map(rethrowFunction(Class::forName))
                  .collect(Collectors.toList());
    }

@Test
public void test_Supplier_with_checked_exceptions() throws ClassNotFoundException {
    Collector.of(
          rethrowSupplier(() -> new StringJoiner(new String(new byte[]{77, 97, 114, 107}, "UTF-8"))),
          StringJoiner::add, StringJoiner::merge, StringJoiner::toString);
    }

@Test    
public void test_uncheck_exception_thrown_by_method() {
    Class clazz1 = uncheck(() -> Class.forName("java.lang.String"));

    Class clazz2 = uncheck(Class::forName, "java.lang.String");
    }

@Test (expected = ClassNotFoundException.class)
public void test_if_correct_exception_is_still_thrown_by_method() {
    Class clazz3 = uncheck(Class::forName, "INVALID");
    }

But don't use it before understanding the following advantages, disadvantages, and limitations:

• If the calling-code is to handle the checked exception you MUST add it to the throws clause of the method that contains the stream. The compiler will not force you to add it anymore, so it's easier to forget it.

• If the calling-code already handles the checked exception, the compiler WILL remind you to add the throws clause to the method declaration that contains the stream (if you don't it will say: Exception is never thrown in body of corresponding try statement).

• In any case, you won't be able to surround the stream itself to catch the checked exception INSIDE the method that contains the stream (if you try, the compiler will say: Exception is never thrown in body of corresponding try statement).

• If you are calling a method which literally can never throw the exception that it declares, then you should not include the throws clause. For example: new String(byteArr, "UTF-8") throws UnsupportedEncodingException, but UTF-8 is guaranteed by the Java spec to always be present. Here, the throws declaration is a nuisance and any solution to silence it with minimal boilerplate is welcome.

• If you hate checked exceptions and feel they should never be added to the Java language to begin with (a growing number of people think this way, and I am NOT one of them), then just don't add the checked exception to the throws clause of the method that contains the stream. The checked exception will, then, behave just like an UNchecked exception.

• If you are implementing a strict interface where you don't have the option for adding a throws declaration, and yet throwing an exception is entirely appropriate, then wrapping an exception just to gain the privilege of throwing it results in a stacktrace with spurious exceptions which contribute no information about what actually went wrong. A good example is Runnable.run(), which does not throw any checked exceptions. In this case, you may decide not to add the checked exception to the throws clause of the method that contains the stream.

• In any case, if you decide NOT to add (or forget to add) the checked exception to the throws clause of the method that contains the stream, be aware of these 2 consequences of throwing CHECKED exceptions:

1) The calling-code won't be able to catch it by name (if you try, the compiler will say: Exception is never thrown in body of corresponding try statement). It will bubble and probably be catched in the main program loop by some "catch Exception" or "catch Throwable", which may be what you want anyway.

2) It violates the principle of least surprise: it will no longer be enough to catch RuntimeException to be able to guarantee catching all possible exceptions. For this reason, I believe this should not be done in framework code, but only in business code that you completely control.

In conclusion: I believe the limitations here are not serious, and the UtilException class may be used without fear. However, it's up to you!

node.js hash string?

If you just want to md5 hash a simple string I found this works for me.

var crypto = require('crypto');
var name = 'braitsch';
var hash = crypto.createHash('md5').update(name).digest('hex');
console.log(hash); // 9b74c9897bac770ffc029102a200c5de

What is a simple command line program or script to backup SQL server databases?

I'm using tsql on a Linux/UNIX infrastructure to access MSSQL databases. Here's a simple shell script to dump a table to a file:

#!/usr/bin/ksh
#
#.....
(
tsql -S {database} -U {user} -P {password} <<EOF
select * from {table}
go
quit
EOF
) >{output_file.dump}

Getting a File's MD5 Checksum in Java

Very fast & clean Java-method that doesn't rely on external libraries:

(Simply replace MD5 with SHA-1, SHA-256, SHA-384 or SHA-512 if you want those)

public String calcMD5() throws Exception{
        byte[] buffer = new byte[8192];
        MessageDigest md = MessageDigest.getInstance("MD5");

        DigestInputStream dis = new DigestInputStream(new FileInputStream(new File("Path to file")), md);
        try {
            while (dis.read(buffer) != -1);
        }finally{
            dis.close();
        }

        byte[] bytes = md.digest();

        // bytesToHex-method
        char[] hexChars = new char[bytes.length * 2];
        for ( int j = 0; j < bytes.length; j++ ) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }

        return new String(hexChars);
}

How to generate a range of numbers between two numbers?

Here is a generic and relatively fast solution that outputs integers from 1 to @n. It works with any positive integer of @n (very large numbers will cause arithmetic overflow) without needing to add or remove table joins. It doesn't require the use of system tables nor do you to change max recursions.

declare @n int = 10000 

;with d as (select * from (values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) x (d)),
n as ( 
    select d x from d where d > 0 and d <= @n
    union all
    select x * 10 + d from n, d where x * 10 + d <= @n
)
select x from n 

You can add an order by clause to sort the numbers.

jQuery UI Alert Dialog as a replacement for alert()

Using some of the info in here I ended up creating my own function to use.

Could be used as...

custom_alert();
custom_alert( 'Display Message' );
custom_alert( 'Display Message', 'Set Title' );

jQuery UI Alert Replacement

function custom_alert( message, title ) {
    if ( !title )
        title = 'Alert';

    if ( !message )
        message = 'No Message to Display.';

    $('<div></div>').html( message ).dialog({
        title: title,
        resizable: false,
        modal: true,
        buttons: {
            'Ok': function()  {
                $( this ).dialog( 'close' );
            }
        }
    });
}

How to restart service using command prompt?

This is my code, to start/stop a Windows service using SC command. If the service fails to start/stop, it will print a log info. You can try it by Inno Setup.

{ start a service }
Exec(ExpandConstant('{cmd}'), '/C sc start ServiceName', '',
     SW_HIDE, ewWaitUntilTerminated, ResultCode);
Log('sc start ServiceName:'+SysErrorMessage(ResultCode));
{ stop a service }
Exec(ExpandConstant('{cmd}'), '/C sc stop ServiceName', '',
     SW_HIDE, ewWaitUntilTerminated, ResultCode);
Log('sc stop ServiceName:'+SysErrorMessage(ResultCode));