Programs & Examples On #Bounded types

jQuery UI Datepicker - Multiple Date Selections

Use this plugin http://multidatespickr.sourceforge.net

  • Select date ranges.
  • Pick multiple dates not in secuence.
  • Define a maximum number of pickable dates.
  • Define a range X days from where it is possible to select Y dates. Define unavailable dates

C++ floating point to integer type conversions

Check out the boost NumericConversion library. It will allow to explicitly control how you want to deal with issues like overflow handling and truncation.

Renaming column names of a DataFrame in Spark Scala

Sometime we have the column name is below format in SQLServer or MySQL table

Ex  : Account Number,customer number

But Hive tables do not support column name containing spaces, so please use below solution to rename your old column names.

Solution:

val renamedColumns = df.columns.map(c => df(c).as(c.replaceAll(" ", "_").toLowerCase()))
df = df.select(renamedColumns: _*)

A child container failed during start java.util.concurrent.ExecutionException

Added AWS dependency and had this error. When I remove it from pom the error is gone. Probably you might have the same situation.

UICollectionView current visible cell index

Swift 5:

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    var visibleRect = CGRect()

    visibleRect.origin = collectionView.contentOffset
    visibleRect.size = collectionView.bounds.size

    let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)

    guard let indexPath = collectionView.indexPathForItem(at: visiblePoint) else { return } 

    print(indexPath)
}

Working Answers Combined In Swift 2.2 :

 func scrollViewDidEndDecelerating(scrollView: UIScrollView) {

        var visibleRect = CGRect()

        visibleRect.origin = self.collectionView.contentOffset
        visibleRect.size = self.collectionView.bounds.size

        let visiblePoint = CGPointMake(CGRectGetMidX(visibleRect), CGRectGetMidY(visibleRect))

        let visibleIndexPath: NSIndexPath = self.collectionView.indexPathForItemAtPoint(visiblePoint)

        guard let indexPath = visibleIndexPath else { return } 
        print(indexPath)

    }

Vim 80 column layout concerns

You also can draw line to see 80 limit:

let &colorcolumn=join(range(81,999),",")
let &colorcolumn="80,".join(range(400,999),",")

Result:

enter image description here

Add custom icons to font awesome

If you want some icons (or all) from font-awesome including yout custom svg icons you can:

1- Go to http://fontawesome.io/ Download the zip and extract-it for example in your Desktop.

2- Go to http://fontastic.me/ use your email to create an account.

3- Once you have been logged-in click on the header option: Add More Icons.

4- Select the SVG of font-awesome located in your extracted zip inside fonts.

5- Repeat the procces uploading your own svg files.

6- Inside Home (at the header of the page) Select the icons you want to download, customize them to give your custom names and select publish to have a link or download the fonts and css.

Sorry about my english ! :D

angularjs ng-style: background-image isn't working

This worked for me, curly braces are not required.

ng-style="{'background-image':'url(../../../app/img/notification/'+notification.icon+'.png)'}"

notification.icon here is scope variable.

PHPMailer - SMTP ERROR: Password command failed when send mail from my server

A bit late, but perhaps someone will find it useful.

Links that fix the problem (you must be logged into google account):

https://security.google.com/settings/security/activity?hl=en&pli=1

https://www.google.com/settings/u/1/security/lesssecureapps

https://accounts.google.com/b/0/DisplayUnlockCaptcha

Some explanation of what happens:

This problem can be caused by either 'less secure' applications trying to use the email account (this is according to google help, not sure how they judge what is secure and what is not) OR if you are trying to login several time in a row OR if you change countries (for example use VPN, move code to different server or actually try to login from different part of the world).

To resolve I had to: (first time)

  • login to my account via web
  • view recent attempts to use the account and accept suspicious access: THIS LINK
  • disable the feature of blocking suspicious apps/technologies: THIS LINK

This worked the first time, but few hours later, probably because I was doing a lot of testing the problem reappeared and was not fixable using the above method. In addition I had to clear the captcha (the funny picture, which asks you to rewrite a word or a sentence when logging into any account nowadays too many times) :

  • after login to my account I went HERE
  • Clicked continue

Hope this helps.

git pull from master into the development branch

Scenario:

I have master updating and my branch updating, I want my branch to keep track of master with rebasing, to keep all history tracked properly, let's call my branch Mybranch

Solution:

git checkout master    
git pull --rebase    
git checkout Mybranch    
git rebase master
git push -f origin Mybranch
  • need to resolve all conflicts with git mergetool &, git rebase --continue, git rebase --skip, git add -u, according to situation and git hints, till all is solved

(correction to last stage, in courtesy of Tzachi Cohen, using "-f" forces git to "update history" at server)

now branch should be aligned with master and rebased, also with remote updated, so at git log there are no "behind" or "ahead", just need to remove all local conflict *.orig files to keep folder "clean"

Change the background color of a row in a JTable

The other answers given here work well since you use the same renderer in every column.

However, I tend to believe that generally when using a JTable you will have different types of data in each columm and therefore you won't be using the same renderer for each column. In these cases you may find the Table Row Rendering approach helpfull.

How to get current available GPUs in tensorflow?

Ensure you have the latest TensorFlow 2.x GPU installed in your GPU supporting machine, Execute the following code in python,

from __future__ import absolute_import, division, print_function, unicode_literals

import tensorflow as tf 

print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))

Will get an output looks like,

2020-02-07 10:45:37.587838: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1006] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-02-07 10:45:37.588896: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1746] Adding visible gpu devices: 0, 1, 2, 3, 4, 5, 6, 7 Num GPUs Available: 8

What is the (best) way to manage permissions for Docker shared volumes?

To share folder between docker host and docker container, try below command

$ docker run -v "$(pwd):$(pwd)" -i -t ubuntu

The -v flag mounts the current working directory into the container. When the host directory of a bind-mounted volume doesn’t exist, Docker will automatically create this directory on the host for you,

However, there are 2 problems we have here:

  1. You cannot write to the volume mounted if you were non-root user because the shared file will be owned by other user in host,
  2. You shouldn't run the process inside your containers as root but even if you run as some hard-coded user it still won't match the user on your laptop/Jenkins,

Solution:

Container: create a user say 'testuser', by default user id will be starting from 1000,

Host: create a group say 'testgroup' with group id 1000, and chown the directory to the new group(testgroup

Reload browser window after POST without prompting user to resend POST data

I had the same problem as you.

Here's what I did (dynamically generated GET form with action set to location.href, hidden input with fresh value), and it seems to work in all browsers:

var elForm=document.createElement("form");
elForm.setAttribute("method", "get");
elForm.setAttribute("action", window.location.href);

var elInputHidden=document.createElement("input");
elInputHidden.setAttribute("type", "hidden");
elInputHidden.setAttribute("name", "r");
elInputHidden.setAttribute("value", new Date().getTime());
elForm.appendChild(elInputHidden);

if(window.location.href.indexOf("?")>=0)
{
    var _arrNameValue;
    var strRequestVars=window.location.href.substr(window.location.href.indexOf("?")+1);
    var _arrRequestVariablePairs=strRequestVars.split("&");
    for(var i=0; i<_arrRequestVariablePairs.length; i++)
    {
        _arrNameValue=_arrRequestVariablePairs[i].split("=");

        elInputHidden=document.createElement("input");
        elInputHidden.setAttribute("type", "hidden");
        elInputHidden.setAttribute("name", decodeURIComponent(_arrNameValue.shift()));
        elInputHidden.setAttribute("value", decodeURIComponent(_arrNameValue.join("=")));
        elForm.appendChild(elInputHidden);
    }
}

document.body.appendChild(elForm);
elForm.submit();

How do I check whether a checkbox is checked in jQuery?

Toggle: 0/1 or else

<input type="checkbox" id="nolunch" />
<input id="checklunch />"

    $('#nolunch').change(function () {
    if ($(this).is(':checked')) {
        $('#checklunch').val('1');
    };
    if ($(this).is(':checked') == false) {
        $('#checklunch').val('0');
    };
});

Minimum and maximum value of z-index?

It depends on the browser (although the latest version of all browsers should max out at 2147483638), as does the browser's reaction when the maximum is exceeded.

http://www.puidokas.com/max-z-index/

is not JSON serializable

class CountryListView(ListView):
     model = Country

    def render_to_response(self, context, **response_kwargs):

         return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json") 

fixed the problem

also mimetype is important.

How to match "any character" in regular expression?

Yes, you can. That should work.

  • . = any char except newline
  • \. = the actual dot character
  • .? = .{0,1} = match any char except newline zero or one times
  • .* = .{0,} = match any char except newline zero or more times
  • .+ = .{1,} = match any char except newline one or more times

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

public String withChars(String inputa) {
    String input = inputa.toLowerCase();
    StringBuilder sb = new StringBuilder();
    final char delim = '_';
    char value;
    boolean capitalize = false;
    for (int i=0; i<input.length(); ++i) {
        value = input.charAt(i);
        if (value == delim) {
            capitalize = true;
        }
        else if (capitalize) {
            sb.append(Character.toUpperCase(value));
            capitalize = false;
        }
        else {
            sb.append(value);
        }
    }

    return sb.toString();
}

public String withRegex(String inputa) {
    String input = inputa.toLowerCase();
    String[] parts = input.split("_");
    StringBuilder sb = new StringBuilder();
    sb.append(parts[0]);
    for (int i=1; i<parts.length; ++i) {
        sb.append(parts[i].substring(0,1).toUpperCase());
        sb.append(parts[i].substring(1));
    }

    return sb.toString();
}

Times: in milli seconds.

Iterations = 1000
WithChars: start = 1379685214671 end = 1379685214683 diff = 12
WithRegex: start = 1379685214683 end = 1379685214712 diff = 29

Iterations = 1000
WithChars: start = 1379685217033 end = 1379685217045 diff = 12
WithRegex: start = 1379685217045 end = 1379685217077 diff = 32

Iterations = 1000
WithChars: start = 1379685218643 end = 1379685218654 diff = 11
WithRegex: start = 1379685218655 end = 1379685218684 diff = 29

Iterations = 1000000
WithChars: start = 1379685232767 end = 1379685232968 diff = 201
WithRegex: start = 1379685232968 end = 1379685233649 diff = 681

Iterations = 1000000
WithChars: start = 1379685237220 end = 1379685237419 diff = 199
WithRegex: start = 1379685237419 end = 1379685238088 diff = 669

Iterations = 1000000
WithChars: start = 1379685239690 end = 1379685239889 diff = 199
WithRegex: start = 1379685239890 end = 1379685240585 diff = 695

Iterations = 1000000000
WithChars: start = 1379685267523 end = 1379685397604 diff = 130081
WithRegex: start = 1379685397605 end = 1379685850582 diff = 452977

How do I convert a file path to a URL in ASP.NET

this is what i use:

private string MapURL(string path)
{
    string appPath = Server.MapPath("/").ToLower();
    return string.Format("/{0}", path.ToLower().Replace(appPath, "").Replace(@"\", "/"));
 }

How to check if input date is equal to today's date?

The Best way and recommended way of comparing date in typescript is:

var today = new Date().getTime();
var reqDateVar = new Date(somedate).getTime();

if(today === reqDateVar){
 // NOW
} else {
 // Some other time
}

Shell script - remove first and last quote (") from a variable

I know this is a very old question, but here is another sed variation, which may be useful to someone. Unlike some of the others, it only replaces double quotes at the start or end...

echo "$opt" | sed -r 's/^"|"$//g'

How to change the colors of a PNG image easily?

Ok guys it can be done easy in photoshop.

Open png photo and then check image -> mode value(i had indexed color). Go image -> mode and check rgb color. Now change your color EASY.

Scanner vs. StringTokenizer vs. String.Split

I recently did some experiments about the bad performance of String.split() in highly performance sensitive situations. You may find this useful.

http://eblog.chrononsystems.com/hidden-evils-of-javas-stringsplit-and-stringr

The gist is that String.split() compiles a Regular Expression pattern each time and can thus slow down your program, compared to if you use a precompiled Pattern object and use it directly to operate on a String.

Laravel back button

<a href="{{ url()->previous() }}" class="btn btn-warning"><i class="fa fa-angle-left"></i> Continue Shopping</a>

This worked in Laravel 5.8

How to pass multiple parameters in json format to a web service using jquery?

Found the solution:

It should be:

"{'Id1':'2','Id2':'2'}"

and not

"{'Id1':'2'},{'Id2':'2'}"

Android Button click go to another xml page

There is more than one way to do this.

Here is a good resource straight from Google: http://developer.android.com/training/basics/firstapp/starting-activity.html

At developer.android.com, they have numerous tutorials explaining just about everything you need to know about android. They even provide detailed API for each class.

If that doesn't help, there are NUMEROUS different resources that can help you with this question and other android questions.

Decrementing for loops

You need to give the range a -1 step

 for i in range(10,0,-1):
    print i

How to test REST API using Chrome's extension "Advanced Rest Client"

With latest ARC for GET request with authentication need to add a raw header named Authorization:authtoken.

Please find the screen shot Get request with authentication and query params

To add Query param click on drop down arrow on left side of URL box.

How to make an HTML back link?

You can also use history.back() alongside document.write() to show link only when there is actually somewhere to go back to:

<script>
  if (history.length > 1) {
    document.write('<a href="javascript:history.back()">Go back</a>');
  }
</script>

shift a std_logic_vector of n bit to right or left

Personally, I think the concatenation is the better solution. The generic implementation would be

entity shifter is
    generic (
        REGSIZE  : integer := 8);
    port(
        clk      : in  str_logic;
        Data_in  : in  std_logic;
        Data_out : out std_logic(REGSIZE-1 downto 0);
end shifter ;

architecture bhv of shifter is
    signal shift_reg : std_logic_vector(REGSIZE-1 downto 0) := (others<='0');
begin
    process (clk) begin
        if rising_edge(clk) then
            shift_reg <= shift_reg(REGSIZE-2 downto 0) & Data_in;
        end if;
    end process;
end bhv;
Data_out <= shift_reg;

Both will implement as shift registers. If you find yourself in need of more shift registers than you are willing to spend resources on (EG dividing 1000 numbers by 4) you might consider using a BRAM to store the values and a single shift register to contain "indices" that result in the correct shift of all the numbers.

JUnit: how to avoid "no runnable methods" in test utils classes

  1. If this is your base test class for example AbstractTest and all your tests extends this then define this class as abstract
  2. If it is Util class then better remove *Test from the class rename it is MyTestUtil or Utils etc.

How to install JRE 1.7 on Mac OS X and use it with Eclipse?

You need to tell Eclipse which JDK/JRE's you have installed and where they are located.

This is somewhat burried in the Eclipse preferences: In the Window-Menu select "Preferences". In the Preferences Tree, open the Node "Java" and select "Installed JRE's". Then click on the "Add"-Button in the Panel and select "Standard VM", "Next" and for "JRE Home" click on the "Directory"-Button and select the top level folder of the JDK you want to add.

Its easier than the description may make it look.

How to downgrade or install an older version of Cocoapods

PROMPT> gem uninstall cocoapods

Select gem to uninstall:
 1. cocoapods-0.32.1
 2. cocoapods-0.33.1
 3. cocoapods-0.36.0.beta.2
 4. cocoapods-0.38.2
 5. cocoapods-0.39.0
 6. cocoapods-1.0.0
 7. All versions
> 6
Successfully uninstalled cocoapods-1.0.0
PROMPT> gem install cocoapods -v 0.39.0
Successfully installed cocoapods-0.39.0
Parsing documentation for cocoapods-0.39.0
Done installing documentation for cocoapods after 1 seconds
1 gem installed
PROMPT> pod --version
0.39.0
PROMPT>

Run jar file in command prompt

Try this

java -jar <jar-file-name>.jar

why does DateTime.ToString("dd/MM/yyyy") give me dd-MM-yyyy?

Add CultureInfo.InvariantCulture as an argument:

using System.Globalization;

...

var dateTime = new DateTime(2016,8,16);
dateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

Will return:

"16/08/2016"

How to delete an app from iTunesConnect / App Store Connect

As the instructions state on the iTuneconnect Developer Guidelines you need to ensure that you are the "team agent" to delete apps. This is stated in the quote below from the developer guidelines.

If the Delete App button isn’t displayed, check that you’re the team agent and that the app is in one of the statuses that allow the app to be deleted.

I have just checked on my account by logging in as the main account holder and the delete button is there for an app that I have previously removed from sale but when I have looked in as another user they don't have this permission, only the main account holder seems to have it.

How to get Printer Info in .NET?

As an alternative to WMI you can get fast accurate results by tapping in to WinSpool.drv (i.e. Windows API) - you can get all the details on the interfaces, structs & constants from pinvoke.net, or I've put the code together at http://delradiesdev.blogspot.com/2012/02/accessing-printer-status-using-winspool.html

Python socket connection timeout

For setting the Socket timeout, you need to follow these steps:

import socket
socks = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socks.settimeout(10.0) # settimeout is the attr of socks.

What are the differences between LinearLayout, RelativeLayout, and AbsoluteLayout?

Definitions:

  • Frame Layout: This is designed to block out an area on the screen to display a single item.
  • Linear Layout: A layout that arranges its children in a single column or a single row.
  • Relative Layout: This layout is a view group that displays child views in relative positions.
  • Table Layout: A layout that arranges its children into rows and columns.

More Information:

FrameLayout

FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other. You can, however, add multiple children to a FrameLayout and control their position within the FrameLayout by assigning gravity to each child, using the android:layout_gravity attribute.

Child views are drawn in a stack, with the most recently added child on top. The size of the FrameLayout is the size of its largest child (plus padding), visible or not (if the FrameLayout's parent permits).

RelativeLayout

A RelativeLayout is a very powerful utility for designing a user interface because it can eliminate nested view groups and keep your layout hierarchy flat, which improves performance. If you find yourself using several nested LinearLayout groups, you may be able to replace them with a single RelativeLayout.

(Current docs here)

TableLayout

A TableLayout consists of a number of TableRow objects, each defining a row (actually, you can have other children, which will be explained below). TableLayout containers do not display border lines for their rows, columns, or cells. Each row has zero or more cells; each cell can hold one View object. The table has as many columns as the row with the most cells. A table can leave cells empty. Cells can span columns, as they can in HTML.

The width of a column is defined by the row with the widest cell in that column.


Note: Absolute Layout is deprecated.

Difference Between $.getJSON() and $.ajax() in jQuery

with $.getJSON()) there is no any error callback only you can track succeed callback and there no standard setting supported like beforeSend, statusCode, mimeType etc, if you want it use $.ajax().

MVC3 EditorFor readOnly

I know the question states MVC 3, but it was 2012, so just in case:

As of MVC 5.1 you can now pass HTML attributes to EditorFor like so:

@Html.EditorFor(x => x.Name, new { htmlAttributes = new { @readonly = "", disabled = "" } })

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

First go to Wamp->Apache->Service->Test Port 80

If its being user by Microsoft HTTPAPI / 2.0

Then the solution is to manually stop the service named web deployment agent service

If you have Microsoft Sql Server installed, even though the IIS service is disabled, it keeps a web service named httpapi2.0 running.

Why can't I duplicate a slice with `copy()`?

If your slices were of the same size, it would work:

arr := []int{1, 2, 3}
tmp := []int{0, 0, 0}
i := copy(tmp, arr)
fmt.Println(i)
fmt.Println(tmp)
fmt.Println(arr)

Would give:

3
[1 2 3]
[1 2 3]

From "Go Slices: usage and internals":

The copy function supports copying between slices of different lengths (it will copy only up to the smaller number of elements)

The usual example is:

t := make([]byte, len(s), (cap(s)+1)*2)
copy(t, s)
s = t

Removing duplicate rows in Notepad++

As of now, it's possible to remove all consecutive duplicate lines with Notepad in-built functionality. Sort the lines first:

Edit > Line Operations > "Sort lines lexicographically",

then

Edit > Line Operations > "Remove Consecutive Duplicate Lines".

The regex solution suggested above didn't remove all duplicate lines for me, but just the consecutive ones as well.

What MIME type should I use for CSV?

For anyone struggling with Google API mimeType for *.csv files. I have found the list of MIME types for google api docs files (look at snipped result)

_x000D_
_x000D_
<table border="1"><thead><tr><th>Google Doc Format</th><th>Conversion Format</th><th>Corresponding MIME type</th></tr></thead><tbody><tr><td>Documents</td><td>HTML</td><td>text/html</td></tr><tr></tr><tr><td></td><td>HTML (zipped)</td><td>application/zip</td></tr><tr><td></td><td>Plain text</td><td>text/plain</td></tr><tr><td></td><td>Rich text</td><td>application/rtf</td></tr><tr><td></td><td>Open Office doc</td><td>application/vnd.oasis.opendocument.text</td></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td></td><td>MS Word document</td><td>application/vnd.openxmlformats-officedocument.wordprocessingml.document</td></tr><tr><td></td><td>EPUB</td><td>application/epub+zip</td></tr><tr><td>Spreadsheets</td><td>MS Excel</td><td>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</td></tr><tr><td></td><td>Open Office sheet</td><td>application/x-vnd.oasis.opendocument.spreadsheet</td></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td></td><td>CSV (first sheet only)</td><td>text/csv</td></tr><tr><td></td><td>TSV (first sheet only)</td><td>text/tab-separated-values</td></tr><tr><td></td><td>HTML (zipped)</td><td>application/zip</td></tr><tr></tr><tr><td>Drawings</td><td>JPEG</td><td>image/jpeg</td></tr><tr><td></td><td>PNG</td><td>image/png</td></tr><tr><td></td><td>SVG</td><td>image/svg+xml</td></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td>Presentations</td><td>MS PowerPoint</td><td>application/vnd.openxmlformats-officedocument.presentationml.presentation</td></tr><tr><td></td><td>Open Office presentation</td><td>application/vnd.oasis.opendocument.presentation</td></tr><tr></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td></td><td>Plain text</td><td>text/plain</td></tr><tr><td>Apps Scripts</td><td>JSON</td><td>application/vnd.google-apps.script+json</td></tr></tbody></table>
_x000D_
_x000D_
_x000D_

Source here: https://developers.google.com/drive/v3/web/manage-downloads#downloading_google_documents the table under: "Google Doc formats and supported export MIME types map to each other as follows"

There is also another list

_x000D_
_x000D_
<table border="1"><thead><tr><th>MIME Type</th><th>Description</th></tr></thead><tbody><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>audio</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>document</span></code></td><td>Google Docs</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>drawing</span></code></td><td>Google Drawing</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>file</span></code></td><td>Google Drive file</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>folder</span></code></td><td>Google Drive folder</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>form</span></code></td><td>Google Forms</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>fusiontable</span></code></td><td>Google Fusion Tables</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>map</span></code></td><td>Google My Maps</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>photo</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>presentation</span></code></td><td>Google Slides</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>script</span></code></td><td>Google Apps Scripts</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>site</span></code></td><td>Google Sites</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>spreadsheet</span></code></td><td>Google Sheets</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>unknown</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>video</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>drive-sdk</span></code></td><td>3rd party shortcut</td></tr></tbody></table>
_x000D_
_x000D_
_x000D_

Source here: https://developers.google.com/drive/v3/web/mime-types

But the first one was more helpful for my use case..

Happy coding ;)

Where to find free public Web Services?

Here you can find some public REST services for encryption and security related things: http://security.jelastic.servint.net

C++ Passing Pointer to Function (Howto) + C++ Pointer Manipulation

void Fun(int *Pointer)
{
  //if you want to manipulate the content of the pointer:
  *Pointer=10;
  //Here we are changing the contents of Pointer to 10
}

* before the pointer means the content of the pointer (except in declarations!)

& before the pointer (or any variable) means the address

EDIT:

int someint=15;
//to call the function
Fun(&someint);
//or we can also do
int *ptr;
ptr=&someint;
Fun(ptr);

An efficient compression algorithm for short text strings

Huffman has a static cost, the Huffman table, so I disagree it's a good choice.

There are adaptative versions which do away with this, but the compression rate may suffer. Actually, the question you should ask is "what algorithm to compress text strings with these characteristics". For instance, if long repetitions are expected, simple Run-Lengh Encoding might be enough. If you can guarantee that only English words, spaces, punctiation and the occasional digits will be present, then Huffman with a pre-defined Huffman table might yield good results.

Generally, algorithms of the Lempel-Ziv family have very good compression and performance, and libraries for them abound. I'd go with that.

With the information that what's being compressed are URLs, then I'd suggest that, before compressing (with whatever algorithm is easily available), you CODIFY them. URLs follow well-defined patterns, and some parts of it are highly predictable. By making use of this knowledge, you can codify the URLs into something smaller to begin with, and ideas behind Huffman encoding can help you here.

For example, translating the URL into a bit stream, you could replace "http" with the bit 1, and anything else with the bit "0" followed by the actual procotol (or use a table to get other common protocols, like https, ftp, file). The "://" can be dropped altogether, as long as you can mark the end of the protocol. Etc. Go read about URL format, and think on how they can be codified to take less space.

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

After looking at all the supplied Versions here, i descided to do one myself, using recursion.

Here is my vb.net Version:

Function CL(ByVal x As Integer) As String
    If x >= 1 And x <= 26 Then
        CL = Chr(x + 64)
    Else
        CL = CL((x - x Mod 26) / 26) & Chr((x Mod 26) + 1 + 64)
    End If
End Function

Can git undo a checkout of unstaged files

An effective savior for this kind of situation is Time Machine (OS X) or a similar time-based backup system. It's saved me a couple of times because I can go back and restore just that one file.

Hosting a Maven repository on github

If you have only aar or jar file itself, or just don't want to use plugins - I've created a simple shell script. You can achieve the same with it - publishing your artifacts to Github and use it as public Maven repo.

Rendering HTML inside textarea

try this example

_x000D_
_x000D_
function toggleRed() {_x000D_
  var text = $('.editable').text();_x000D_
  $('.editable').html('<p style="color:red">' + text + '</p>');_x000D_
}_x000D_
_x000D_
function toggleItalic() {_x000D_
  var text = $('.editable').text();_x000D_
  $('.editable').html("<i>" + text + "</i>");_x000D_
}_x000D_
_x000D_
$('.bold').click(function() {_x000D_
  toggleRed();_x000D_
});_x000D_
_x000D_
$('.italic').click(function() {_x000D_
  toggleItalic();_x000D_
});
_x000D_
.editable {_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
  border: 1px solid #ccc;_x000D_
  padding: 5px;_x000D_
  resize: both;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="editable" contenteditable="true"></div>_x000D_
<button class="bold">toggle red</button>_x000D_
<button class="italic">toggle italic</button>
_x000D_
_x000D_
_x000D_

do { ... } while (0) — what is it good for?

It helps to group multiple statements into a single one so that a function-like macro can actually be used as a function. Suppose you have:

#define FOO(n)   foo(n);bar(n)

and you do:

void foobar(int n) {
  if (n)
     FOO(n);
}

then this expands to:

void foobar(int n) {
  if (n)
     foo(n);bar(n);
}

Notice that the second call bar(n) is not part of the if statement anymore.

Wrap both into do { } while(0), and you can also use the macro in an if statement.

jQuery get mouse position within an element

I would suggest this:

e.pageX - this.getBoundingClientRect().left

Replace multiple characters in one replace call

Here's a simple way to do it without RegEx.
You can prototype and/or cache things as desired.

// Example: translate( 'faded', 'abcdef', '123456' ) returns '61454'
function translate( s, sFrom, sTo ){
    for ( var out = '', i = 0; i < s.length; i++ ){
        out += sTo.charAt( sFrom.indexOf( s.charAt(i) ));
    }
    return out;
}

Global variables in c#.net

I second jdk's answer: any public static member of any class of your application can be considered as a "global variable".

However, do note that this is an ASP.NET application, and as such, it's a multi-threaded context for your global variables. Therefore, you should use some locking mechanism when you update and/or read the data to/from these variables. Otherwise, you might get your data in a corrupted state.

SQL Server : Columns to Rows

The opposite of this is to flatten a column into a csv eg

SELECT STRING_AGG ([value],',') FROM STRING_SPLIT('Akio,Hiraku,Kazuo', ',')

SQL Format as of Round off removing decimals

check the round function and how does the length argument works. It controls the behaviour of the precision of the result

How line ending conversions work with git core.autocrlf between different operating systems

The best explanation of how core.autocrlf works is found on the gitattributes man page, in the text attribute section.

This is how core.autocrlf appears to work currently (or at least since v1.7.2 from what I am aware):

  • core.autocrlf = true
  1. Text files checked-out from the repository that have only LF characters are normalized to CRLF in your working tree; files that contain CRLF in the repository will not be touched
  2. Text files that have only LF characters in the repository, are normalized from CRLF to LF when committed back to the repository. Files that contain CRLF in the repository will be committed untouched.
  • core.autocrlf = input
  1. Text files checked-out from the repository will keep original EOL characters in your working tree.
  2. Text files in your working tree with CRLF characters are normalized to LF when committed back to the repository.
  • core.autocrlf = false
  1. core.eol dictates EOL characters in the text files of your working tree.
  2. core.eol = native by default, which means Windows EOLs are CRLF and *nix EOLs are LF in working trees.
  3. Repository gitattributes settings determines EOL character normalization for commits to the repository (default is normalization to LF characters).

I've only just recently researched this issue and I also find the situation to be very convoluted. The core.eol setting definitely helped clarify how EOL characters are handled by git.

How to run an .ipynb Jupyter Notebook from terminal?

For new version instead of:

ipython nbconvert --to python <YourNotebook>.ipynb

You can use jupyter instend of ipython:

jupyter nbconvert --to python <YourNotebook>.ipynb

Using PHP to upload file and add the path to MySQL database

mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;

These are deprecated use the following..

 // Connects to your Database
            $link = mysqli_connect("localhost", "root", "", "");

and to insert data use the following

 $sql = "INSERT INTO  Table-Name (Column-Name)
VALUES ('$filename')" ;

How to make a drop down list in yii2?

It seems you've found your answer already but since you mentioned the active form I'll contribute with one more, even if it differs only ever so slightly.

<?php
    $form = ActiveForm::begin();

    echo $form->field($model, 'attribute')
        ->dropDownList(
            $items,           // Flat array ('id'=>'label')
            ['prompt'=>'']    // options
        );

    ActiveForm::end();
?>

Converting PHP result array to JSON

$result = mysql_query($query) or die("Data not found."); 
$rows=array(); 
while($r=mysql_fetch_assoc($result))
{ 
$rows[]=$r;
}
header("Content-type:application/json"); 
echo json_encode($rows);

How to generate a unique hash code for string input in android...?

It depends on what you mean:

  • As mentioned String.hashCode() gives you a 32 bit hash code.

  • If you want (say) a 64-bit hashcode you can easily implement it yourself.

  • If you want a cryptographic hash of a String, the Java crypto libraries include implementations of MD5, SHA-1 and so on. You'll typically need to turn the String into a byte array, and then feed that to the hash generator / digest generator. For example, see @Bryan Kemp's answer.

  • If you want a guaranteed unique hash code, you are out of luck. Hashes and hash codes are non-unique.

A Java String of length N has 65536 ^ N possible states, and requires an integer with 16 * N bits to represent all possible values. If you write a hash function that produces integer with a smaller range (e.g. less than 16 * N bits), you will eventually find cases where more than one String hashes to the same integer; i.e. the hash codes cannot be unique. This is called the Pigeonhole Principle, and there is a straight forward mathematical proof. (You can't fight math and win!)

But if "probably unique" with a very small chance of non-uniqueness is acceptable, then crypto hashes are a good answer. The math will tell you how big (i.e. how many bits) the hash has to be to achieve a given (low enough) probability of non-uniqueness.

Can you create nested WITH clauses for Common Table Expressions?

These answers are pretty good, but as far as getting the items to order properly, you'd be better off looking at this article http://dataeducation.com/dr-output-or-how-i-learned-to-stop-worrying-and-love-the-merge

Here's an example of his query.

WITH paths AS ( 
    SELECT 
        EmployeeID, 
        CONVERT(VARCHAR(900), CONCAT('.', EmployeeID, '.')) AS FullPath 
    FROM EmployeeHierarchyWide 
    WHERE ManagerID IS NULL

    UNION ALL

    SELECT 
        ehw.EmployeeID, 
        CONVERT(VARCHAR(900), CONCAT(p.FullPath, ehw.EmployeeID, '.')) AS FullPath 
    FROM paths AS p 
        JOIN EmployeeHierarchyWide AS ehw ON ehw.ManagerID = p.EmployeeID 
) 
SELECT * FROM paths order by FullPath

How to insert TIMESTAMP into my MySQL table?

Please try CURRENT_TIME() or now() functions

"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', NOW(), '$comments')"

OR

"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', CURRENT_TIME(), '$comments')"

OR you could try with PHP date function here:

$date = date("Y-m-d H:i:s");

How to create a oracle sql script spool file

To spool from a BEGIN END block is pretty simple. For example if you need to spool result from two tables into a file, then just use the for loop. Sample code is given below.

BEGIN

FOR x IN 
(
    SELECT COLUMN1,COLUMN2 FROM TABLE1
    UNION ALL
    SELECT COLUMN1,COLUMN2 FROM TABLEB
)    
LOOP
    dbms_output.put_line(x.COLUMN1 || '|' || x.COLUMN2);
END LOOP;

END;
/

Get the position of a div/span tag

As Alex noted you can use jQuery offset() to get the position relative to the document flow. Use position() for its x,y coordinates relative to the parent.

EDIT: Switched document.ready for window.load because load waits for all of the elements so you get their size instead of simply preparing the DOM. In my experience, load results in fewer incorrectly Javascript positioned elements.

$(window).load(function(){ 
  // Log the position with jQuery
  var position = $('#myDivInQuestion').position();
  console.log('X: ' + position.left + ", Y: " + position.top );
});

Trimming text strings in SQL Server 2008

No Answer is true

The true Answer is Edit Column to NVARCHAR and you found Automatically trim Execute but this code UPDATE Table SET Name = RTRIM(LTRIM(Name)) use it only with Nvarchar if use it with CHAR or NCHAR it will not work

javascript toISOString() ignores timezone offset

My solution without using moment is to convert it to a timestamp, add the timezone offset, then convert back to a date object, and then run the toISOString()

var date = new Date(); // Or the date you'd like converted.
var isoDateTime = new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString();

C# delete a folder and all files and folders within that folder

The Directory.Delete method has a recursive boolean parameter, it should do what you need

How to pass in password to pg_dump?

Backup over ssh with password using temporary .pgpass credentials and push to S3:

#!/usr/bin/env bash
cd "$(dirname "$0")"

DB_HOST="*******.*********.us-west-2.rds.amazonaws.com"
DB_USER="*******"
SSH_HOST="[email protected]_domain.com"
BUCKET_PATH="bucket_name/backup"

if [ $# -ne 2 ]; then
    echo "Error: 2 arguments required"
    echo "Usage:"
    echo "  my-backup-script.sh <DB-name> <password>"
    echo "  <DB-name> = The name of the DB to backup"
    echo "  <password> = The DB password, which is also used for GPG encryption of the backup file"
    echo "Example:"
    echo "  my-backup-script.sh my_db my_password"
    exit 1
fi

DATABASE=$1
PASSWORD=$2

echo "set remote PG password .."
echo "$DB_HOST:5432:$DATABASE:$DB_USER:$PASSWORD" | ssh "$SSH_HOST" "cat > ~/.pgpass; chmod 0600 ~/.pgpass"
echo "backup over SSH and gzip the backup .."
ssh "$SSH_HOST" "pg_dump -U $DB_USER -h $DB_HOST -C --column-inserts $DATABASE" | gzip > ./tmp.gz
echo "unset remote PG password .."
echo "*********" | ssh "$SSH_HOST" "cat > ~/.pgpass"
echo "encrypt the backup .."
gpg --batch --passphrase "$PASSWORD" --cipher-algo AES256 --compression-algo BZIP2 -co "$DATABASE.sql.gz.gpg" ./tmp.gz

# Backing up to AWS obviously requires having your credentials to be set locally
# EC2 instances can use instance permissions to push files to S3
DATETIME=`date "+%Y%m%d-%H%M%S"`
aws s3 cp ./"$DATABASE.sql.gz.gpg" s3://"$BUCKET_PATH"/"$DATABASE"/db/"$DATETIME".sql.gz.gpg
# s3 is cheap, so don't worry about a little temporary duplication here
# "latest" is always good to have because it makes it easier for dev-ops to use
aws s3 cp ./"$DATABASE.sql.gz.gpg" s3://"$BUCKET_PATH"/"$DATABASE"/db/latest.sql.gz.gpg

echo "local clean-up .."
rm ./tmp.gz
rm "$DATABASE.sql.gz.gpg"

echo "-----------------------"
echo "To decrypt and extract:"
echo "-----------------------"
echo "gpg -d ./$DATABASE.sql.gz.gpg | gunzip > tmp.sql"
echo

Just substitute the first couple of config lines with whatever you need - obviously. For those not interested in the S3 backup part, take it out - obviously.

This script deletes the credentials in .pgpass afterward because in some environments, the default SSH user can sudo without a password, for example an EC2 instance with the ubuntu user, so using .pgpass with a different host account in order to secure those credential, might be pointless.

Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to

You should upgrade the version of gradle. for example: com.android.build.gradle 1.3.0

this issue occurs when version of the gradle is changed.

How do I send a file as an email attachment using Linux command line?

Mailutils makes this a piece of cake

echo "Body" | mail.mailutils -M -s "My Subject" -A attachment.pdf [email protected]
  • -A file attaches a file
  • -M enables MIME, so that you can have an attachment and plaintext body.

If not yet installed, run

sudo apt install mailutils

Turn off warnings and errors on PHP and MySQL

If you can't get to your php.ini file for some reason, disable errors to stdout (display_errors) in a .htaccess file in any directory by adding the following line:

php_flag display_errors off

additionally, you can add error logging to a file:

php_flag log_errors on

Removing "bullets" from unordered list <ul>

ul.menu li a:before, ul.menu li .item:before, ul.menu li .separator:before {
  content: "\2022";
  font-family: FontAwesome;
  margin-right: 10px;
  display: inline;
  vertical-align: middle;
  font-size: 1.6em;
  font-weight: normal;
}

Is present in your site's CSS, looks like it's coming from a compiled CSS file from within your application. Perhaps from a plugin. Changing the name of the "menu" class you are using should resolve the issue.

Visual for you - http://i.imgur.com/d533SQD.png

Logical operator in a handlebars.js {{#if}} conditional

Here's an approach I'm using for ember 1.10 and ember-cli 2.0.

// app/helpers/js-x.js
export default Ember.HTMLBars.makeBoundHelper(function (params) {
  var paramNames = params.slice(1).map(function(val, idx) { return "p" + idx; });
  var func = Function.apply(this, paramNames.concat("return " + params[0] + ";"))
  return func.apply(params[1] === undefined ? this : params[1], params.slice(1));
});

Then you can use it in your templates like this:

// used as sub-expression
{{#each item in model}}
  {{#if (js-x "this.section1 || this.section2" item)}}
  {{/if}}
{{/each}}

// used normally
{{js-x "p0 || p1" model.name model.offer.name}}

Where the arguments to the expression are passed in as p0,p1,p2 etc and p0 can also be referenced as this.

How to pass data from child component to its parent in ReactJS?

You can create the state in the ParentComponent using useState and pass down the setIsParentData function as prop into the ChildComponent.

In the ChildComponent, update the data using the received function through prop to send the data back to ParentComponent.

I use this technique especially when my code in the ParentComponent is getting too long, therefore I will create child components from the ParentComponent. Typically, it will be only 1 level down and using useContext or redux seems overkill in order to share states between components.

ParentComponent.js

import React, { useState } from 'react';
import ChildComponent from './ChildComponent';

export function ParentComponent(){
  const [isParentData, setIsParentData] = useState(True);

  return (
    <p>is this a parent data?: {isParentData}</p>
    <ChildComponent toChild={isParentData} sendToParent={setIsParentData} />
  );
}

ChildComponent.js

import React from 'react';

export function ChildComponent(props){

  return (
    <button onClick={() => {props.sendToParent(False)}}>Update</button>
    <p>The state of isParentData is {props.toChild}</p>
  );
};

Android ListView with different layouts for each row

Since you know how many types of layout you would have - it's possible to use those methods.

getViewTypeCount() - this methods returns information how many types of rows do you have in your list

getItemViewType(int position) - returns information which layout type you should use based on position

Then you inflate layout only if it's null and determine type using getItemViewType.

Look at this tutorial for further information.

To achieve some optimizations in structure that you've described in comment I would suggest:

  • Storing views in object called ViewHolder. It would increase speed because you won't have to call findViewById() every time in getView method. See List14 in API demos.
  • Create one generic layout that will conform all combinations of properties and hide some elements if current position doesn't have it.

I hope that will help you. If you could provide some XML stub with your data structure and information how exactly you want to map it into row, I would be able to give you more precise advise. By pixel.

read word by word from file in C++

what you are doing here is reading one character at a time from the input stream and assume that all the characters between " " represent a word. BUT it's unlikely to be a " " after the last word, so that's probably why it does not work:

"word1 word2 word2EOF"

How to call getResources() from a class which has no context?

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. It is an "interface" that allows access to application specific resources and class and information about application environment. Your activities and services also extend Context to they inherit all those methods to access the environment information in which the application is running.

This means you must have to pass context to the specific class if you want to get/modify some specific information about the resources. You can pass context in the constructor like

public classname(Context context, String s1) 
{
...
}

How to get a cross-origin resource sharing (CORS) post request working

REQUEST:

 $.ajax({
            url: "http://localhost:8079/students/add/",
            type: "POST",
            crossDomain: true,
            data: JSON.stringify(somejson),
            dataType: "json",
            success: function (response) {
                var resp = JSON.parse(response)
                alert(resp.status);
            },
            error: function (xhr, status) {
                alert("error");
            }
        });

RESPONSE:

response = HttpResponse(json.dumps('{"status" : "success"}'))
response.__setitem__("Content-type", "application/json")
response.__setitem__("Access-Control-Allow-Origin", "*")

return response

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

The datasource is by default .\SQLEXPRESS (its the instance where databases are placed by default) or if u changed the name of the instance during installation of sql server so i advise you to do this :

connectionString="Data Source=.\\yourInstance(defaulT Data source is SQLEXPRESS);
       Initial Catalog=databaseName;
       User ID=theuser if u use it;
       Password=thepassword if u use it;
       integrated security=true(if u don t use user and pass; else change it false)"

Without to knowing your instance, I could help with this one. Hope it helped

Can an ASP.NET MVC controller return an Image?

you can use File to return a file like View, Content etc

 public ActionResult PrintDocInfo(string Attachment)
            {
                string test = Attachment;
                if (test != string.Empty || test != "" || test != null)
                {
                    string filename = Attachment.Split('\\').Last();
                    string filepath = Attachment;
                    byte[] filedata = System.IO.File.ReadAllBytes(Attachment);
                    string contentType = MimeMapping.GetMimeMapping(Attachment);

                    System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
                    {
                        FileName = filename,
                        Inline = true,
                    };

                    Response.AppendHeader("Content-Disposition", cd.ToString());

                    return File(filedata, contentType);          
                }
                else { return Content("<h3> Patient Clinical Document Not Uploaded</h3>"); }

            }

bootstrap 3 tabs not working properly

When I removed the smooth scroll script (https://github.com/cferdinandi/smooth-scroll), it worked.

iptables block access to port 8000 except from IP address

You can always use iptables to delete the rules. If you have a lot of rules, just output them using the following command.

iptables-save > myfile

vi to edit them from the commend line. Just use the "dd" to delete the lines you no longer want.

iptables-restore < myfile and you're good to go.  

REMEMBER THAT IF YOU DON'T CONFIGURE YOUR OS TO SAVE THE RULES TO A FILE AND THEN LOAD THE FILE DURING THE BOOT THAT YOUR RULES WILL BE LOST.

CreateProcess error=2, The system cannot find the file specified

My recomendation is to keep the getRuntime().exec because exec uses the ProcessBuilder.

Try

 p=r.exec(new String[] {"winrar", "x", "h:\\myjar.jar", "*.*", "h:\\new"}, null, dir);

What should be the package name of android app?

Presently Package name starting with "com.example" is not allowed to upload in the app -store. Otherwise , all other package names starting with "com" are allowed .

Build and Install unsigned apk on device without the development server?

There are two extensions you can use for this. This is added to react-native for setting these:

  1. disableDevInDebug: true: Disables dev server in debug buildType
  2. bundleInDebug: true: Adds jsbundle to debug buildType.

So, your final project.ext.react in android/app/build.gradle should look like below

project.ext.react = [
    enableHermes: false,  // clean and rebuild if changing
    devDisabledInDev: true, // Disable dev server in dev release
    bundleInDev: true, // add bundle to dev apk
]

What does "wrong number of arguments (1 for 0)" mean in Ruby?

I assume you called a function with an argument which was defined without taking any.

def f()
  puts "hello world"
end

f(1)   # <= wrong number of arguments (1 for 0)

How to use the CancellationToken property?

You have to pass the CancellationToken to the Task, which will periodically monitors the token to see whether cancellation is requested.

// CancellationTokenSource provides the token and have authority to cancel the token
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;  

// Task need to be cancelled with CancellationToken 
Task task = Task.Run(async () => {     
  while(!token.IsCancellationRequested) {
      Console.Write("*");         
      await Task.Delay(1000);
  }
}, token);

Console.WriteLine("Press enter to stop the task"); 
Console.ReadLine(); 
cancellationTokenSource.Cancel(); 

In this case, the operation will end when cancellation is requested and the Task will have a RanToCompletion state. If you want to be acknowledged that your task has been cancelled, you have to use ThrowIfCancellationRequested to throw an OperationCanceledException exception.

Task task = Task.Run(async () =>             
{                 
    while (!token.IsCancellationRequested) {
         Console.Write("*");                      
         await Task.Delay(1000);                
    }           
    token.ThrowIfCancellationRequested();               
}, token)
.ContinueWith(t =>
 {
      t.Exception?.Handle(e => true);
      Console.WriteLine("You have canceled the task");
 },TaskContinuationOptions.OnlyOnCanceled);  
 
Console.WriteLine("Press enter to stop the task");                 
Console.ReadLine();                 
cancellationTokenSource.Cancel();                 
task.Wait(); 

Hope this helps to understand better.

Normalizing images in OpenCV

If you want to change the range to [0, 1], make sure the output data type is float.

image = cv2.imread("lenacolor512.tiff", cv2.IMREAD_COLOR)  # uint8 image
norm_image = cv2.normalize(image, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)

Get resultset from oracle stored procedure

FYI as of Oracle 12c, you can do this:

CREATE OR REPLACE PROCEDURE testproc(n number)
AS
  cur SYS_REFCURSOR;
BEGIN
    OPEN cur FOR SELECT object_id,object_name from all_objects where rownum < n;
    DBMS_SQL.RETURN_RESULT(cur);
END;
/

EXEC testproc(3);

OBJECT_ID OBJECT_NAME                                                                                                                     
---------- ------------
100 ORA$BASE                                                                                                                        
116 DUAL                                                                                                                            

This was supposed to get closer to other databases, and ease migrations. But it's not perfect to me, for instance SQL developer won't display it nicely as a normal SELECT.

I prefer the output of pipeline functions, but they need more boilerplate to code.

more info: https://oracle-base.com/articles/12c/implicit-statement-results-12cr1

What is sys.maxint in Python 3?

As pointed out by others, Python 3's int does not have a maximum size, but if you just need something that's guaranteed to be higher than any other int value, then you can use the float value for Infinity, which you can get with float("inf").

Intellij Idea: Importing Gradle project - getting JAVA_HOME not defined yet

For Windows Platform:

try Running the 64 Bit exe version of IntelliJ from a path similar to following.

note that it is available beside the default idea.exe

"C:\Program Files (x86)\JetBrains\IntelliJ IDEA 15.0\bin\idea64.exe"

link

How to set background image in Java?

The answer will vary slightly depending on whether the application or applet is using AWT or Swing.

(Basically, classes that start with J such as JApplet and JFrame are Swing, and Applet and Frame are AWT.)

In either case, the basic steps would be:

  1. Draw or load an image into a Image object.
  2. Draw the background image in the painting event of the Component you want to draw the background in.

Step 1. Loading the image can be either by using the Toolkit class or by the ImageIO class.

The Toolkit.createImage method can be used to load an Image from a location specified in a String:

Image img = Toolkit.getDefaultToolkit().createImage("background.jpg");

Similarly, ImageIO can be used:

Image img = ImageIO.read(new File("background.jpg");

Step 2. The painting method for the Component that should get the background will need to be overridden and paint the Image onto the component.

For AWT, the method to override is the paint method, and use the drawImage method of the Graphics object that is handed into the paint method:

public void paint(Graphics g)
{
    // Draw the previously loaded image to Component.
    g.drawImage(img, 0, 0, null);

    // Draw sprites, and other things.
    // ....
}

For Swing, the method to override is the paintComponent method of the JComponent, and draw the Image as with what was done in AWT.

public void paintComponent(Graphics g)
{
    // Draw the previously loaded image to Component.
    g.drawImage(img, 0, 0, null);

    // Draw sprites, and other things.
    // ....
}

Simple Component Example

Here's a Panel which loads an image file when instantiated, and draws that image on itself:

class BackgroundPanel extends Panel
{
    // The Image to store the background image in.
    Image img;
    public BackgroundPanel()
    {
        // Loads the background image and stores in img object.
        img = Toolkit.getDefaultToolkit().createImage("background.jpg");
    }

    public void paint(Graphics g)
    {
        // Draws the img to the BackgroundPanel.
        g.drawImage(img, 0, 0, null);
    }
}

For more information on painting:

Comprehensive beginner's virtualenv tutorial?

For setting up virtualenv on a clean Ubuntu installation, I found this zookeeper tutorial to be the best - you can ignore the parts about zookeper itself. The virtualenvwrapper documentation offers similar content, but it's a bit scarce on telling you what exactly to put into your .bashrc file.

Find all elements with a certain attribute value in jquery

It's not called a tag; what you're looking for is called an html attribute.

$('div[imageId="imageN"]').each(function(i,el){
  $(el).html('changes');
  //do what ever you wish to this object :) 
});

Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

1. A Buffer is just a view for looking into an ArrayBuffer.

A Buffer, in fact, is a FastBuffer, which extends (inherits from) Uint8Array, which is an octet-unit view (“partial accessor”) of the actual memory, an ArrayBuffer.

  /lib/buffer.js#L65-L73 Node.js 9.4.0
class FastBuffer extends Uint8Array {
  constructor(arg1, arg2, arg3) {
    super(arg1, arg2, arg3);
  }
}
FastBuffer.prototype.constructor = Buffer;
internalBuffer.FastBuffer = FastBuffer;

Buffer.prototype = FastBuffer.prototype;

2. The size of an ArrayBuffer and the size of its view may vary.

Reason #1: Buffer.from(arrayBuffer[, byteOffset[, length]]).

With Buffer.from(arrayBuffer[, byteOffset[, length]]), you can create a Buffer with specifying its underlying ArrayBuffer and the view's position and size.

const test_buffer = Buffer.from(new ArrayBuffer(50), 40, 10);
console.info(test_buffer.buffer.byteLength); // 50; the size of the memory.
console.info(test_buffer.length); // 10; the size of the view.

Reason #2: FastBuffer's memory allocation.

It allocates the memory in two different ways depending on the size.

  • If the size is less than the half of the size of a memory pool and is not 0 (“small”): it makes use of a memory pool to prepare the required memory.
  • Else: it creates a dedicated ArrayBuffer that exactly fits the required memory.
  /lib/buffer.js#L306-L320 Node.js 9.4.0
function allocate(size) {
  if (size <= 0) {
    return new FastBuffer();
  }
  if (size < (Buffer.poolSize >>> 1)) {
    if (size > (poolSize - poolOffset))
      createPool();
    var b = new FastBuffer(allocPool, poolOffset, size);
    poolOffset += size;
    alignPool();
    return b;
  } else {
    return createUnsafeBuffer(size);
  }
}
  /lib/buffer.js#L98-L100 Node.js 9.4.0
function createUnsafeBuffer(size) {
  return new FastBuffer(createUnsafeArrayBuffer(size));
}

What do you mean by a “memory pool?”

A memory pool is a fixed-size pre-allocated memory block for keeping small-size memory chunks for Buffers. Using it keeps the small-size memory chunks tightly together, so prevents fragmentation caused by separate management (allocation and deallocation) of small-size memory chunks.

In this case, the memory pools are ArrayBuffers whose size is 8 KiB by default, which is specified in Buffer.poolSize. When it is to provide a small-size memory chunk for a Buffer, it checks if the last memory pool has enough available memory to handle this; if so, it creates a Buffer that “views” the given partial chunk of the memory pool, otherwise, it creates a new memory pool and so on.


You can access the underlying ArrayBuffer of a Buffer. The Buffer's buffer property (that is, inherited from Uint8Array) holds it. A “small” Buffer's buffer property is an ArrayBuffer that represents the entire memory pool. So in this case, the ArrayBuffer and the Buffer varies in size.

const zero_sized_buffer = Buffer.allocUnsafe(0);
const small_buffer = Buffer.from([0xC0, 0xFF, 0xEE]);
const big_buffer = Buffer.allocUnsafe(Buffer.poolSize >>> 1);

// A `Buffer`'s `length` property holds the size, in octets, of the view.
// An `ArrayBuffer`'s `byteLength` property holds the size, in octets, of its data.

console.info(zero_sized_buffer.length); /// 0; the view's size.
console.info(zero_sized_buffer.buffer.byteLength); /// 0; the memory..'s size.
console.info(Buffer.poolSize); /// 8192; a memory pool's size.

console.info(small_buffer.length); /// 3; the view's size.
console.info(small_buffer.buffer.byteLength); /// 8192; the memory pool's size.
console.info(Buffer.poolSize); /// 8192; a memory pool's size.

console.info(big_buffer.length); /// 4096; the view's size.
console.info(big_buffer.buffer.byteLength); /// 4096; the memory's size.
console.info(Buffer.poolSize); /// 8192; a memory pool's size.

3. So we need to extract the memory it “views.”

An ArrayBuffer is fixed in size, so we need to extract it out by making a copy of the part. To do this, we use Buffer's byteOffset property and length property, which are inherited from Uint8Array, and the ArrayBuffer.prototype.slice method, which makes a copy of a part of an ArrayBuffer. The slice()-ing method herein was inspired by @ZachB.

const test_buffer = Buffer.from(new ArrayBuffer(10));
const zero_sized_buffer = Buffer.allocUnsafe(0);
const small_buffer = Buffer.from([0xC0, 0xFF, 0xEE]);
const big_buffer = Buffer.allocUnsafe(Buffer.poolSize >>> 1);

function extract_arraybuffer(buf)
{
    // You may use the `byteLength` property instead of the `length` one.
    return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
}

// A copy -
const test_arraybuffer = extract_arraybuffer(test_buffer); // of the memory.
const zero_sized_arraybuffer = extract_arraybuffer(zero_sized_buffer); // of the... void.
const small_arraybuffer = extract_arraybuffer(small_buffer); // of the part of the memory.
const big_arraybuffer = extract_arraybuffer(big_buffer); // of the memory.

console.info(test_arraybuffer.byteLength); // 10
console.info(zero_sized_arraybuffer.byteLength); // 0
console.info(small_arraybuffer.byteLength); // 3
console.info(big_arraybuffer.byteLength); // 4096

4. Performance improvement

If you're to use the results as read-only, or it is okay to modify the input Buffers' contents, you can avoid unnecessary memory copying.

const test_buffer = Buffer.from(new ArrayBuffer(10));
const zero_sized_buffer = Buffer.allocUnsafe(0);
const small_buffer = Buffer.from([0xC0, 0xFF, 0xEE]);
const big_buffer = Buffer.allocUnsafe(Buffer.poolSize >>> 1);

function obtain_arraybuffer(buf)
{
    if(buf.length === buf.buffer.byteLength)
    {
        return buf.buffer;
    } // else:
    // You may use the `byteLength` property instead of the `length` one.
    return buf.subarray(0, buf.length);
}

// Its underlying `ArrayBuffer`.
const test_arraybuffer = obtain_arraybuffer(test_buffer);
// Just a zero-sized `ArrayBuffer`.
const zero_sized_arraybuffer = obtain_arraybuffer(zero_sized_buffer);
// A copy of the part of the memory.
const small_arraybuffer = obtain_arraybuffer(small_buffer);
// Its underlying `ArrayBuffer`.
const big_arraybuffer = obtain_arraybuffer(big_buffer);

console.info(test_arraybuffer.byteLength); // 10
console.info(zero_sized_arraybuffer.byteLength); // 0
console.info(small_arraybuffer.byteLength); // 3
console.info(big_arraybuffer.byteLength); // 4096

How to change date format from DD/MM/YYYY or MM/DD/YYYY to YYYY-MM-DD?

String dt = Date.Now.ToString("yyyy-MM-dd");

Now you got this for dt, 2010-09-09

Open Form2 from Form1, close Form1 from Form2

Your question is vague but you could use ShowDialog to display form 2. Then when you close form 2, pass a DialogResult object back to let the user know how the form was closed - if the user clicked the button, then close form 1 as well.

Redirect from an HTML page

You can do it in javascript:

location = "url";

Angular2 - Radio Button Binding

[value]="item" using *ngFor also works with Reactive Forms in Angular 2 and 4

<label *ngFor="let item of items">
    <input type="radio" formControlName="options" [value]="item">
    {{item}}
</label>`

Difference between SRC and HREF

Simple Definition

SRC : (Source). To specify the origin of (a communication); document:     

HREF : (Hypertext Reference). A reference or link to another page, document...

Replace duplicate spaces with a single space in T-SQL

Please Find below code

select trim(string_agg(value,' ')) from STRING_SPLIT('  single    spaces   only  ',' ')
where value<>' '

This worked for me.. Hope this helps...

PostgreSQL database default location on Linux

/var/lib/postgresql/[version]/data/

At least in Gentoo Linux and Ubuntu 14.04 by default.

You can find postgresql.conf and look at param data_directory. If it is commented then database directory is the same as this config file directory.

Notepad++: Multiple words search in a file (may be in different lines)?

You need a new version of notepad++. Looks like old versions don't support |.

Note: egrep "CAT|TOWN" will search for lines containing CATOWN. (CAT)|(TOWN) is the proper or extension (matching 1,3,4). Strangely you wrote and which is btw (CAT.*TOWN)|(TOWN.*CAT)

PHP function to generate v4 UUID

From tom, on http://www.php.net/manual/en/function.uniqid.php

$r = unpack('v*', fread(fopen('/dev/random', 'r'),16));
$uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
    $r[1], $r[2], $r[3], $r[4] & 0x0fff | 0x4000,
    $r[5] & 0x3fff | 0x8000, $r[6], $r[7], $r[8])

ini_set("memory_limit") in PHP 5.3.3 is not working at all

If you have the suhosin extension enabled, it can prevent scripts from setting the memory limit beyond what it started with or some defined cap.

http://www.hardened-php.net/suhosin/configuration.html#suhosin.memory_limit

Count distinct value pairs in multiple columns in SQL

You can also do something like:

SELECT COUNT(DISTINCT id + name + address) FROM mytable

How to remove an HTML element using Javascript?

I'm still a newbie too, but here is one simple and easy way: You can use outerHTML, which is the whole tag, not just a portion:

EX: <tag id='me'>blahblahblah</tag>'s innerHTML would be blahblahblah, and outerHTML would be the whole thing, <tag id='me'>blahblahblah</tag>.


So, for the example, if you want to delete the tag, it's basically deleting its data, so if you change the outerHTML to an empty string, it's like deleting it.

<body>
    <p id="myTag">This is going to get removed...</p>
    <input type="button" onclick="javascript:
        document.getElementById('myTag').outerHTML = '';//this makes the outerHTML (the whole tag, not what is inside it)
    " value="Remove Praragraph">
</body>

Instead, if you want to just not display it, you can style it in JS using the visibility, opacity, and display properties.

document.getElementById('foo').style.visibility = hidden;
//or
document.getElementById('foo').style.opacity = 0;
//or
document.getElementById('foo').style.display = none;



Note that opacity makes the element still display, just you can't see it as much. Also, you can select text, copy, paste, and do everything you could normally do, even though it's invisible.
Visibility fits your situation more, but it will leave a blank transparent space as big as the element it was applied to.
I would recommend you do display, depending on how you make your webpage. Display basically deleting the element from your view, but you can still see it in DevTools. Hope this helps!

How to change the default charset of a MySQL table?

You can change the default with an alter table set default charset but that won't change the charset of the existing columns. To change that you need to use a alter table modify column.

Changing the charset of a column only means that it will be able to store a wider range of characters. Your application talks to the db using the mysql client so you may need to change the client encoding as well.

Align a div to center

This worked for me..

div.className {
display: inline-block;
margin: auto;
}

Curl command without using cache

The -H 'Cache-Control: no-cache' argument is not guaranteed to work because the remote server or any proxy layers in between can ignore it. If it doesn't work, you can do it the old-fashioned way, by adding a unique querystring parameter. Usually, the servers/proxies will think it's a unique URL and not use the cache.

curl "http://www.example.com?foo123"

You have to use a different querystring value every time, though. Otherwise, the server/proxies will match the cache again. To automatically generate a different querystring parameter every time, you can use date +%s, which will return the seconds since epoch.

curl "http://www.example.com?$(date +%s)"

Set LIMIT with doctrine 2?

Your setMaxResults($limit) needs to be set on the object.

e.g.

$query_ids = $this->getEntityManager()
  ->createQuery(
    "SELECT e_.id
    FROM MuzichCoreBundle:Element e_
    WHERE [...]
    GROUP BY e_.id")
;
$query_ids->setMaxResults($limit);

How do I set/unset a cookie with jQuery?

I thought Vignesh Pichamani's answer was the simplest and cleanest. Just adding to his the ability to set the number of days before expiration:

EDIT: also added 'never expires' option if no day number is set

        function setCookie(key, value, days) {
            var expires = new Date();
            if (days) {
                expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
                document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
            } else {
                document.cookie = key + '=' + value + ';expires=Fri, 30 Dec 9999 23:59:59 GMT;';
            }
        }

        function getCookie(key) {
            var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
            return keyValue ? keyValue[2] : null;
        }

Set the cookie:

setCookie('myData', 1, 30); // myData=1 for 30 days. 
setCookie('myData', 1); // myData=1 'forever' (until the year 9999) 

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

Write HTML string in JSON

You should escape the forward slash too, here is the correct JSON:

[{
"id": "services.html",
"img": "img/SolutionInnerbananer.jpg",
"html": "<h2class=\"fg-white\">AboutUs<\/h2><pclass=\"fg-white\">developing and supporting complex IT solutions.Touchingmillions of lives world wide by bringing in innovative technology <\/p>"
}]

How to get a reference to an iframe's window object inside iframe's onload handler created from parent window

You're declaring everything in the parent page. So the references to window and document are to the parent page's. If you want to do stuff to the iframe's, use iframe || iframe.contentWindow to access its window, and iframe.contentDocument || iframe.contentWindow.document to access its document.

There's a word for what's happening, possibly "lexical scope": What is lexical scope?

The only context of a scope is this. And in your example, the owner of the method is doc, which is the iframe's document. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.

This is how I would write it:

(function () {
  var dom, win, doc, where, iframe;

  iframe = document.createElement('iframe');
  iframe.src = "javascript:false";

  where = document.getElementsByTagName('script')[0];
  where.parentNode.insertBefore(iframe, where);

  win = iframe.contentWindow || iframe;
  doc = iframe.contentDocument || iframe.contentWindow.document;

  doc.open();
  doc._l = (function (w, d) {
    return function () {
      w.vanishing_global = new Date().getTime();

      var js = d.createElement("script");
      js.src = 'test-vanishing-global.js?' + w.vanishing_global;

      w.name = "foobar";
      d.foobar = "foobar:" + Math.random();
      d.foobar = "barfoo:" + Math.random();
      d.body.appendChild(js);
    };
  })(win, doc);
  doc.write('<body onload="document._l();"></body>');
  doc.close();
})();

The aliasing of win and doc as w and d aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe's stuff. If you want to access the parent's, you still use window and document.

I'm not sure what the implications are of adding methods to a document (doc in this case), but it might make more sense to set the _l method on win. That way, things can be run without a prefix...such as <body onload="_l();"></body>

Path.Combine for URLs?

Well, I just concatenate two strings and use regular expressions to do the cleaning part.

    public class UriTool
    {
        public static Uri Join(string path1, string path2)
        {
            string url = path1 + "/" + path2;
            url = Regex.Replace(url, "(?<!http:)/{2,}", "/");

            return new Uri(url);
        }
    }

So, you can use it like this:

    string path1 = "http://someaddress.com/something/";
    string path2 = "/another/address.html";
    Uri joinedUri = UriTool.Join(path1, path2);

    // joinedUri.ToString() returns "http://someaddress.com/something/another/address.html"

Python: CSV write by column rather than row

Let's assume that (1) you don't have a large memory (2) you have row headings in a list (3) all the data values are floats; if they're all integers up to 32- or 64-bits worth, that's even better.

On a 32-bit Python, storing a float in a list takes 16 bytes for the float object and 4 bytes for a pointer in the list; total 20. Storing a float in an array.array('d') takes only 8 bytes. Increasingly spectacular savings are available if all your data are int (any negatives?) that will fit in 8, 4, 2 or 1 byte(s) -- especially on a recent Python where all ints are longs.

The following pseudocode assumes floats stored in array.array('d'). In case you don't really have a memory problem, you can still use this method; I've put in comments to indicate the changes needed if you want to use a list.

# Preliminary:
import array # list: delete
hlist = []
dlist = []
for each row: 
    hlist.append(some_heading_string)
    dlist.append(array.array('d')) # list: dlist.append([])
# generate data
col_index = -1
for each column:
    col_index += 1
    for row_index in xrange(len(hlist)):
        v = calculated_data_value(row_index, colindex)
        dlist[row_index].append(v)
# write to csv file
for row_index in xrange(len(hlist)):
    row = [hlist[row_index]]
    row.extend(dlist[row_index])
    csv_writer.writerow(row)

pandas resample documentation

B         business day frequency
C         custom business day frequency (experimental)
D         calendar day frequency
W         weekly frequency
M         month end frequency
SM        semi-month end frequency (15th and end of month)
BM        business month end frequency
CBM       custom business month end frequency
MS        month start frequency
SMS       semi-month start frequency (1st and 15th)
BMS       business month start frequency
CBMS      custom business month start frequency
Q         quarter end frequency
BQ        business quarter endfrequency
QS        quarter start frequency
BQS       business quarter start frequency
A         year end frequency
BA, BY    business year end frequency
AS, YS    year start frequency
BAS, BYS  business year start frequency
BH        business hour frequency
H         hourly frequency
T, min    minutely frequency
S         secondly frequency
L, ms     milliseconds
U, us     microseconds
N         nanoseconds

See the timeseries documentation. It includes a list of offsets (and 'anchored' offsets), and a section about resampling.

Note that there isn't a list of all the different how options, because it can be any NumPy array function and any function that is available via groupby dispatching can be passed to how by name.

How to use multiple @RequestMapping annotations in spring?

It's better to use PathVariable annotation if you still want to get the uri which was called.

@PostMapping("/pub/{action:a|b|c}")
public JSONObject handlexxx(@PathVariable String action, @RequestBody String reqStr){
...
}

or parse it from request object.

Resolve promises one after another (i.e. in sequence)?

Simple util for standard Node.js promise:

function sequence(tasks, fn) {
    return tasks.reduce((promise, task) => promise.then(() => fn(task)), Promise.resolve());
}

UPDATE

items-promise is a ready to use NPM package doing the same.

Implementing two interfaces in a class with same method. Which interface method is overridden?

Try implementing the interface as anonymous.

public class MyClass extends MySuperClass implements MyInterface{

MyInterface myInterface = new MyInterface(){

/* Overrided method from interface */
@override
public void method1(){

}

};

/* Overrided method from superclass*/
@override
public void method1(){

}

}

How can I list all tags for a Docker image on a remote registry?

If the JSON parsing tool, jq is available

wget -q https://registry.hub.docker.com/v1/repositories/debian/tags -O - | \
    jq -r '.[].name'

SQL Server procedure declare a list

That is not possible with a normal query since the in clause needs separate values and not a single value containing a comma separated list. One solution would be a dynamic query

declare @myList varchar(100)
set @myList = '(1,2,5,7,10)'
exec('select * from DBTable where id IN ' + @myList)

how to specify new environment location for conda create

While using the --prefix option works, you have to explicitly use it every time you create an environment. If you just want your environments stored somewhere else by default, you can configure it in your .condarc file.

Please see: https://conda.io/docs/user-guide/configuration/use-condarc.html#specify-environment-directories-envs-dirs

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

In my case TLS1_2 was enabled both on client and server but the server was using MD5 while client disabled it. So, test both client and server on http://ssllabs.com or test using openssl/s_client to see what's happening. Also, check the selected cipher using Wireshark.

Build Step Progress Bar (css and jquery)

This is what I did:

  1. Create jQuery .progressbar() to load a div into a progress bar.
  2. Create the step title on the bottom of the progress bar. Position them with CSS.
  3. Then I create function in jQuery that change the value of the progressbar everytime user move on to next step.

HTML

<div id="divProgress"></div>
<div id="divStepTitle">
    <span class="spanStep">Step 1</span> <span class="spanStep">Step 2</span> <span class="spanStep">Step 3</span>
</div>

<input type="button" id="btnPrev" name="btnPrev" value="Prev" />
<input type="button" id="btnNext" name="btnNext" value="Next" />

CSS

#divProgress
{
    width: 600px;
}

#divStepTitle
{
    width: 600px;
}

.spanStep
{
    text-align: center;
    width: 200px;
}

Javascript/jQuery

var progress = 0;

$(function({
    //set step progress bar
    $("#divProgress").progressbar();

    //event handler for prev and next button
    $("#btnPrev, #btnNext").click(function(){
        step($(this));
    });
});

function step(obj)
{
    //switch to prev/next page
    if (obj.val() == "Prev")
    {
        //set new value for progress bar
        progress -= 20;
        $("#divProgress").progressbar({ value: progress });

        //do extra step for showing previous page
    }
    else if (obj.val() == "Next")
    {
        //set new value for progress bar
        progress += 20;
        $("#divProgress").progressbar({ value: progress });

        //do extra step for showing next page
    }
}

Is it possible to disable the network in iOS Simulator?

You can throttle the internet connection with a 3rd party app such as

Charles: http://www.charlesproxy.com/

Hit command + shift + T on a Mac to setup the throttling.

Replacing column values in a pandas DataFrame

Using Series.map with Series.fillna

If your column contains more strings than only female and male, Series.map will fail in this case since it will return NaN for other values.

That's why we have to chain it with fillna:

Example why .map fails:

df = pd.DataFrame({'female':['male', 'female', 'female', 'male', 'other', 'other']})

   female
0    male
1  female
2  female
3    male
4   other
5   other
df['female'].map({'female': '1', 'male': '0'})

0      0
1      1
2      1
3      0
4    NaN
5    NaN
Name: female, dtype: object

For the correct method, we chain map with fillna, so we fill the NaN with values from the original column:

df['female'].map({'female': '1', 'male': '0'}).fillna(df['female'])

0        0
1        1
2        1
3        0
4    other
5    other
Name: female, dtype: object

How do you run multiple programs in parallel from a bash script?

With GNU Parallel http://www.gnu.org/software/parallel/ it is as easy as:

(echo prog1; echo prog2) | parallel

Or if you prefer:

parallel ::: prog1 prog2

Learn more:

Call two functions from same onclick

onclick="pay(); cls();"

however, if you're using a return statement in "pay" function the execution will stop and "cls" won't execute,

a workaround to this:

onclick="var temp = function1();function2(); return temp;"

Print new output on same line

Similar to what has been suggested, you can do:

print(i, end=',')

Output: 0,1,2,3,

Can not connect to local PostgreSQL

I had similar problem when trying to use postgresql with rails. Updating my Gemfile to use new version of gem pg solve this problem for me. (gem pg version 0.16.0 works). In the Gemfile use:

gem 'pg', '0.16.0'

then run the following to update the gem

bundle install --without production
bundle update
bundle install

Rails how to run rake task

In rails 4.2 the above methods didn't work.

  1. Go to the Terminal.
  2. Change the directory to the location where your rake file is present.
  3. run rake task_name.
  4. In the above case, run rake iqmedier - will run only iqmedir task.
  5. run rake euroads - will run only the euroads task.
  6. To Run all the tasks in that file assign the following inside the same file and run rake all

    task :all => [:iqmedier, :euroads, :mikkelsen, :orville ] do #This will print all the tasks o/p on the screen 
    end
    

using jQuery .animate to animate a div from right to left?

This worked for me

$("div").css({"left":"2000px"}).animate({"left":"0px"}, "slow");

Scroll to the top of the page using JavaScript?

<script>

  $("a[href='#top']").click(function() {
     $("html, body").animate({ scrollTop: 0 }, "slow");
     return false;
  });
</script>

in html

<a href="#top">go top</a>

Rails: Can't verify CSRF token authenticity when making a POST request

There is relevant info on a configuration of CSRF with respect to API controllers on api.rubyonrails.org:

?

It's important to remember that XML or JSON requests are also affected and if you're building an API you should change forgery protection method in ApplicationController (by default: :exception):

class ApplicationController < ActionController::Base
  protect_from_forgery unless: -> { request.format.json? }
end

We may want to disable CSRF protection for APIs since they are typically designed to be state-less. That is, the request API client will handle the session for you instead of Rails.

?

What does "exec sp_reset_connection" mean in Sql Server Profiler?

Note however:

If you issue SET TRANSACTION ISOLATION LEVEL in a stored procedure or trigger, when the object returns control the isolation level is reset to the level in effect when the object was invoked. For example, if you set REPEATABLE READ in a batch, and the batch then calls a stored procedure that sets the isolation level to SERIALIZABLE, the isolation level setting reverts to REPEATABLE READ when the stored procedure returns control to the batch.

http://msdn.microsoft.com/en-us/library/ms173763.aspx

What is the difference between field, variable, attribute, and property in Java POJOs?

  • variable - named storage address. Every variable has a type which defines a memory size, attributes and behaviours. There are for types of Java variables: class variable, instance variable, local variable, method parameter
//pattern
<Java_type> <name> ;

//for example
int myInt;
String myString;
CustomClass myCustomClass;
  • field - member variable or data member. It is a variable inside a class(class variable or instance variable)

  • attribute - in some articles you can find that attribute it is an object representation of class variable. Object operates by attributes which define a set of characteristics.

CustomClass myCustomClass = new CustomClass();
myCustomClass.myAttribute = "poor fantasy"; //`myAttribute` is an attribute of `myCustomClass` object with a "poor fantasy" value
  • property - field + bounded getter/setter. It has a field syntax but uses methods under the hood. Java does not support it in pure form. Take a look at Objective-C, Swift, Kotlin

For example Kotlin sample:

//field - Backing Field
class Person {
    var name: String = "default name"
        get() = field
        set(value) { field = value }
}

//using
val person = Person()
person.name = "Alex"    // setter is used
println(person.name)    // getter is used

[Swift variable, property...]

Can we install Android OS on any Windows Phone and vice versa, and same with iPhone and vice versa?

Ok, For installing Android on Windows phone, I think you can..(But your window phone has required configuration to run Android) (For other I don't know If I will then surely post here)

Just go through these links,

Run Android on Your Windows Mobile Phone

full tutorial on how to put android on windows mobile touch pro 2

How to install Android on most Windows Mobile phones

Update:

For Windows 7 to Android device, this also possible, (You need to do some hack for this)

Just go through these links,

Install Windows Phone 7 Mango on HTC HD2 [How-To Guide]

HTC HD2: How To Install WP7 (Windows Phone 7) & MAGLDR 1.13 To NAND

Install windows phone 7 on android and iphones | Tips and Tricks

How to install Windows Phone 7 on HTC HD2? (Video)


To Install Android on your iOS Devices (This also possible...)

Look at How To Install Android on your iOS Devices

Android 2.2 Froyo running on Iphone

Interface/enum listing standard mime-type constants

There's also a MediaType class in androidannotations in case you want to use with android! See here.

Form onSubmit determine which submit button was pressed

Bare bones, but confirmed working, example:

<script type="text/javascript">
var clicked;
function mysubmit() {
    alert(clicked);
}
</script>
<form action="" onsubmit="mysubmit();return false">
    <input type="submit" onclick="clicked='Save'" value="Save" />
    <input type="submit" onclick="clicked='Add'" value="Add" />
</form>

Reading int values from SqlDataReader

you can use

reader.GetInt32(3);

to read an 32 bit int from the data reader.

If you know the type of your data I think its better to read using the Get* methods which are strongly typed rather than just reading an object and casting.

Have you considered using

reader.GetInt32(reader.GetOrdinal(columnName)) 

rather than accessing by position. This makes your code less brittle and will not break if you change the query to add new columns before the existing ones. If you are going to do this in a loop, cache the ordinal first.

Android sample bluetooth code to send a simple string via bluetooth

private OutputStream outputStream;
private InputStream inStream;

private void init() throws IOException {
    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if (blueAdapter != null) {
        if (blueAdapter.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();

            if(bondedDevices.size() > 0) {
                Object[] devices = (Object []) bondedDevices.toArray();
                BluetoothDevice device = (BluetoothDevice) devices[position];
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                outputStream = socket.getOutputStream();
                inStream = socket.getInputStream();
            }

            Log.e("error", "No appropriate paired devices.");
        } else {
            Log.e("error", "Bluetooth is disabled.");
        }
    }
}

public void write(String s) throws IOException {
    outputStream.write(s.getBytes());
}

public void run() {
    final int BUFFER_SIZE = 1024;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytes = 0;
    int b = BUFFER_SIZE;

    while (true) {
        try {
            bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

What is the difference between Document style and RPC style communication?

I think what you are asking is the difference between RPC Literal, Document Literal and Document Wrapped SOAP web services.

Note that Document web services are delineated into literal and wrapped as well and they are different - one of the primary difference is that the latter is BP 1.1 compliant and the former is not.

Also, in Document Literal the operation to be invoked is not specified in terms of its name whereas in Wrapped, it is. This, I think, is a significant difference in terms of easily figuring out the operation name that the request is for.

In terms of RPC literal versus Document Wrapped, the Document Wrapped request can be easily vetted / validated against the schema in the WSDL - one big advantage.

I would suggest using Document Wrapped as the web service type of choice due to its advantages.

SOAP on HTTP is the SOAP protocol bound to HTTP as the carrier. SOAP could be over SMTP or XXX as well. SOAP provides a way of interaction between entities (client and servers, for example) and both entities can marshal operation arguments / return values as per the semantics of the protocol.

If you were using XML over HTTP (and you can), it is simply understood to be XML payload on HTTP request / response. You would need to provide the framework to marshal / unmarshal, error handling and so on.

A detailed tutorial with examples of WSDL and code with emphasis on Java: SOAP and JAX-WS, RPC versus Document Web Services

How to install xgboost in Anaconda Python (Windows platform)?

I figured out easy way to install XgBoost by mix of what is mentioned here.

Step 1: Install gitbash from here and start gitbash.

Step 2: git clone --recursive https://github.com/dmlc/xgboost

Step 3: git submodule init

       git submodule update

step 4: alias make='mingw32-make'

step 5: cp make/mingw64.mk config.mk; make -j4

step 6: Goto Anaconda prompt and if you have a conda environment then activate that environment like my was py35 so I activate it by typing activate py35

cd python-package
python setup.py install

step 7: setup the Path in system environment variable to the path where you installed xgboost/python-package.

Implementing a Custom Error page on an ASP.Net website

Try this way, almost same.. but that's what I did, and working.

<configuration>
    <system.web>
       <customErrors mode="On" defaultRedirect="apperror.aspx">
          <error statusCode="404" redirect="404.aspx" />
          <error statusCode="500" redirect="500.aspx" />
       </customErrors>
    </system.web>
</configuration> 

or try to change the 404 error page from IIS settings, if required urgently.

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

In the controller add following lines when you make the cunstructor

i.e, after

parent::Controller();

add below lines

    $this->load->helper('lang_translate');
    $this->lang->load('nl_site', 'nl'); // ('filename', 'directory')

create helper file lang_translate_helper.php with following function and put it in directory system\application\helpers

function label($label, $obj)
{
    $return = $obj->lang->line($label);
    if($return)
        echo $return;
    else
        echo $label;
}

for each of the language, create a directory with language abbrevation like en, nl, fr, etc., under system\application\languages

create language file in above (respective) directory which will contain $lang array holding pairs label=>language_value as given below

nl_site_lang.php

$lang['welcome'] = 'Welkom';
$lang['hello word'] = 'worde Witaj';

en_site_lang.php

$lang['welcome'] = 'Welcome';
$lang['hello word'] = 'Hello Word';

you can store multiple files for same language with differently as per the requirement e.g, if you want separate language file for managing backend (administrator section) you can use it in controller as $this->lang->load('nl_admin', 'nl');

nl_admin_lang.php

$lang['welcome'] = 'Welkom';
$lang['hello word'] = 'worde Witaj';

and finally to print the label in desired language, access labels as below in view

label('welcome', $this);

OR

label('hello word', $this);

note the space in hello & word you can use it like this way as well :)

whene there is no lable defined in the language file, it will simply print it what you passed to the function label.

Netbeans installation doesn't find JDK

Set JAVA_HOME in environment variable.

set JAVA_HOME to only JDK1.6.0_23 or whatever jdk folder you have. dont include bin folder in path.

PHP Redirect to another page after form submit

Right after @mail($email_to, $email_subject, $email_message, $headers);

header('Location: nextpage.php');

Note that you will never see 'Thanks for subscribing to our mailing list'

That should be on the next page, if you echo any text you will get an error because the headers would have been already created, if you want to redirect never return any text, not even a space!

Extract substring using regexp in plain bash

Using pure :

$ cat file.txt
US/Central - 10:26 PM (CST)
$ while read a b time x; do [[ $b == - ]] && echo $time; done < file.txt

another solution with bash regex :

$ [[ "US/Central - 10:26 PM (CST)" =~ -[[:space:]]*([0-9]{2}:[0-9]{2}) ]] &&
    echo ${BASH_REMATCH[1]}

another solution using grep and look-around advanced regex :

$ echo "US/Central - 10:26 PM (CST)" | grep -oP "\-\s+\K\d{2}:\d{2}"

another solution using sed :

$ echo "US/Central - 10:26 PM (CST)" |
    sed 's/.*\- *\([0-9]\{2\}:[0-9]\{2\}\).*/\1/'

another solution using perl :

$ echo "US/Central - 10:26 PM (CST)" |
    perl -lne 'print $& if /\-\s+\K\d{2}:\d{2}/'

and last one using awk :

$ echo "US/Central - 10:26 PM (CST)" |
    awk '{for (i=0; i<=NF; i++){if ($i == "-"){print $(i+1);exit}}}'

Remove empty array elements

Just want to contribute an alternative to loops...also addressing gaps in keys...

In my case I wanted to keep sequential array keys when the operation was complete (not just odd numbers, which is what I was staring at. Setting up code to look just for odd keys seemed fragile to me and not future-friendly.)

I was looking for something more like this: http://gotofritz.net/blog/howto/removing-empty-array-elements-php/

The combination of array_filter and array_slice does the trick.

$example = array_filter($example); $example = array_slice($example,0);

No idea on efficiencies or benchmarks but it works.

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

I am not sure and not really trust $_SERVER['HTTP_HOST'] because it depend on header from client. In another way, if a domain requested by client is not mine one, they will not getting into my site because DNS and TCP/IP protocol point it to the correct destination. However I don't know if possible to hijack the DNS, network or even Apache server. To be safe, I define host name in environment and compare it with $_SERVER['HTTP_HOST'].

Add SetEnv MyHost domain.com in .htaccess file on root and add ths code in Common.php

if (getenv('MyHost')!=$_SERVER['HTTP_HOST']) {
  header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request');
  exit();
}

I include this Common.php file in every php page. This page doing anything required for each request like session_start(), modify session cookie and reject if post method come from different domain.

Java: JSON -> Protobuf & back conversion

Here is my utility class, you may use:

package <removed>;
import com.google.protobuf.Message;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.util.JsonFormat;
/**
 * Author @espresso stackoverflow.
 * Sample use:
 *      Model.Person reqObj = ProtoUtil.toProto(reqJson, Model.Person.getDefaultInstance());
        Model.Person res = personSvc.update(reqObj);
        final String resJson = ProtoUtil.toJson(res);
 **/
public class ProtoUtil {
    public static <T extends Message> String toJson(T obj){
        try{
            return JsonFormat.printer().print(obj);
        }catch(Exception e){
            throw new RuntimeException("Error converting Proto to json", e);
        }
    }
   public static <T extends MessageOrBuilder> T toProto(String protoJsonStr, T message){
        try{
            Message.Builder builder = message.getDefaultInstanceForType().toBuilder();
            JsonFormat.parser().ignoringUnknownFields().merge(protoJsonStr,builder);
            T out = (T) builder.build();
            return out;
        }catch(Exception e){
            throw new RuntimeException(("Error converting Json to proto", e);
        }
    }
}

What is the equivalent to getch() & getche() in Linux?

#include <termios.h>
#include <stdio.h>

static struct termios old, current;

/* Initialize new terminal i/o settings */
void initTermios(int echo) 
{
  tcgetattr(0, &old); /* grab old terminal i/o settings */
  current = old; /* make new settings same as old settings */
  current.c_lflag &= ~ICANON; /* disable buffered i/o */
  if (echo) {
      current.c_lflag |= ECHO; /* set echo mode */
  } else {
      current.c_lflag &= ~ECHO; /* set no echo mode */
  }
  tcsetattr(0, TCSANOW, &current); /* use these new terminal i/o settings now */
}

/* Restore old terminal i/o settings */
void resetTermios(void) 
{
  tcsetattr(0, TCSANOW, &old);
}

/* Read 1 character - echo defines echo mode */
char getch_(int echo) 
{
  char ch;
  initTermios(echo);
  ch = getchar();
  resetTermios();
  return ch;
}

/* Read 1 character without echo */
char getch(void) 
{
  return getch_(0);
}

/* Read 1 character with echo */
char getche(void) 
{
  return getch_(1);
}

/* Let's test it out */
int main(void) {
  char c;
  printf("(getche example) please type a letter: ");
  c = getche();
  printf("\nYou typed: %c\n", c);
  printf("(getch example) please type a letter...");
  c = getch();
  printf("\nYou typed: %c\n", c);
  return 0;
}

Output:

(getche example) please type a letter: g
You typed: g
(getch example) please type a letter...
You typed: g

How to Create simple drag and Drop in angularjs

I just posted this to my brand spanking new blog: http://jasonturim.wordpress.com/2013/09/01/angularjs-drag-and-drop/

Code here: https://github.com/logicbomb/lvlDragDrop

Demo here: http://logicbomb.github.io/ng-directives/drag-drop.html

Here are the directives these rely on a UUID service which I've included below:

var module = angular.module("lvl.directives.dragdrop", ['lvl.services']);

module.directive('lvlDraggable', ['$rootScope', 'uuid', function($rootScope, uuid) {
        return {
            restrict: 'A',
            link: function(scope, el, attrs, controller) {
                console.log("linking draggable element");

                angular.element(el).attr("draggable", "true");
                var id = attrs.id;
                if (!attrs.id) {
                    id = uuid.new()
                    angular.element(el).attr("id", id);
                }

                el.bind("dragstart", function(e) {
                    e.dataTransfer.setData('text', id);

                    $rootScope.$emit("LVL-DRAG-START");
                });

                el.bind("dragend", function(e) {
                    $rootScope.$emit("LVL-DRAG-END");
                });
            }
        }
    }]);

module.directive('lvlDropTarget', ['$rootScope', 'uuid', function($rootScope, uuid) {
        return {
            restrict: 'A',
            scope: {
                onDrop: '&'
            },
            link: function(scope, el, attrs, controller) {
                var id = attrs.id;
                if (!attrs.id) {
                    id = uuid.new()
                    angular.element(el).attr("id", id);
                }

                el.bind("dragover", function(e) {
                  if (e.preventDefault) {
                    e.preventDefault(); // Necessary. Allows us to drop.
                  }

                  e.dataTransfer.dropEffect = 'move';  // See the section on the DataTransfer object.
                  return false;
                });

                el.bind("dragenter", function(e) {
                  // this / e.target is the current hover target.
                  angular.element(e.target).addClass('lvl-over');
                });

                el.bind("dragleave", function(e) {
                  angular.element(e.target).removeClass('lvl-over');  // this / e.target is previous target element.
                });

                el.bind("drop", function(e) {
                  if (e.preventDefault) {
                    e.preventDefault(); // Necessary. Allows us to drop.
                  }

                  if (e.stopPropagation) {
                    e.stopPropagation(); // Necessary. Allows us to drop.
                  }
                    var data = e.dataTransfer.getData("text");
                    var dest = document.getElementById(id);
                    var src = document.getElementById(data);

                    scope.onDrop({dragEl: src, dropEl: dest});
                });

                $rootScope.$on("LVL-DRAG-START", function() {
                    var el = document.getElementById(id);
                    angular.element(el).addClass("lvl-target");
                });

                $rootScope.$on("LVL-DRAG-END", function() {
                    var el = document.getElementById(id);
                    angular.element(el).removeClass("lvl-target");
                    angular.element(el).removeClass("lvl-over");
                });
            }
        }
    }]);

UUID service

angular
.module('lvl.services',[])
.factory('uuid', function() {
    var svc = {
        new: function() {
            function _p8(s) {
                var p = (Math.random().toString(16)+"000000000").substr(2,8);
                return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p ;
            }
            return _p8() + _p8(true) + _p8(true) + _p8();
        },

        empty: function() {
          return '00000000-0000-0000-0000-000000000000';
        }
    };

    return svc;
});

How to create a new branch from a tag?

If you simply want to create a new branch without immediately changing to it, you could do the following:

git branch newbranch v1.0

How to find Oracle Service Name

Connect to the server as "system" using SID. Execute this query:

select value from v$parameter where name like '%service_name%';

It worked for me.

What is the difference between baud rate and bit rate?

The bit rate is a measure of the number of bits that are transmitted per unit of time.

The baud rate, which is also known as symbol rate, measures the number of symbols that are transmitted per unit of time. A symbol typically consists of a fixed number of bits depending on what the symbol is defined as(for example 8bit or 9bit data). The baud rate is measured in symbols per second.

Take an example, where an ascii character 'R' is transmitted over a serial channel every one second.

The binary equivalent is 01010010.

So in this case, the baud rate is 1(one symbol transmitted per second) and the bit rate is 8 (eight bits are transmitted per second).

How to concatenate columns in a Postgres SELECT?

it is better to use CONCAT function in PostgreSQL for concatenation

eg : select CONCAT(first_name,last_name) from person where pid = 136

if you are using column_a || ' ' || column_b for concatenation for 2 column , if any of the value in column_a or column_b is null query will return null value. which may not be preferred in all cases.. so instead of this

||

use

CONCAT

it will return relevant value if either of them have value

Java BigDecimal: Round to the nearest whole value

You can use setScale() to reduce the number of fractional digits to zero. Assuming value holds the value to be rounded:

BigDecimal scaled = value.setScale(0, RoundingMode.HALF_UP);
System.out.println(value + " -> " + scaled);

Using round() is a bit more involved as it requires you to specify the number of digits to be retained. In your examples this would be 3, but this is not valid for all values:

BigDecimal rounded = value.round(new MathContext(3, RoundingMode.HALF_UP));
System.out.println(value + " -> " + rounded);

(Note that BigDecimal objects are immutable; both setScale and round will return a new object.)

Sending a JSON HTTP POST request from Android

try some thing like blow:

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

wr.writeBytes(jsonParam.toString());

wr.flush();
wr.close();

References :

  1. http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
  2. Java - sending HTTP parameters via POST method easily

How can I change the Bootstrap default font family using font from Google?

I think the best and cleanest way would be to get a custom download of bootstrap.

http://getbootstrap.com/customize/

You can then change the font-defaults in the Typography (in that link). This then gives you a .Less file that you can make further changes to defaults with later.

How to check if a file exists in a shell script

Internally, the rm command must test for file existence anyway,
so why add another test? Just issue

rm filename

and it will be gone after that, whether it was there or not.
Use rm -f is you don't want any messages about non-existent files.

If you need to take some action if the file does NOT exist, then you must test for that yourself. Based on your example code, this is not the case in this instance.

Python list sort in descending order

Here is another way


timestamps.sort()
timestamps.reverse()
print(timestamps)

Curl error 60, SSL certificate issue: self signed certificate in certificate chain

Error: SSL certificate problem: self signed certificate in certificate chain

Solution:
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);    
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

Return array in a function

$8.3.5/8 states-

"Functions shall not have a return type of type array or function, although they may have a return type of type pointer or reference to such things. There shall be no arrays of functions, although there can be arrays of pointers to functions."

int (&fn1(int (&arr)[5]))[5]{     // declare fn1 as returning refernce to array
   return arr;
}

int *fn2(int arr[]){              // declare fn2 as returning pointer to array
   return arr;
}


int main(){
   int buf[5];
   fn1(buf);
   fn2(buf);
}

Java: parse int value from a char

By simply subtracting by char '0'(zero) a char (of digit '0' to '9') can be converted into int(0 to 9), e.g., '5'-'0' gives int 5.

String str = "123";

int a=str.charAt(1)-'0';

How can I send an HTTP POST request to a server from Excel using VBA?

If you need it to work on both Mac and Windows, you can use QueryTables:

With ActiveSheet.QueryTables.Add(Connection:="URL;http://carbon.brighterplanet.com/flights.txt", Destination:=Range("A2"))
    .PostText = "origin_airport=MSN&destination_airport=ORD"
    .RefreshStyle = xlOverwriteCells
    .SaveData = True
    .Refresh
End With

Notes:

  • Regarding output... I don't know if it's possible to return the results to the same cell that called the VBA function. In the example above, the result is written into A2.
  • Regarding input... If you want the results to refresh when you change certain cells, make sure those cells are the argument to your VBA function.
  • This won't work on Excel for Mac 2008, which doesn't have VBA. Excel for Mac 2011 got VBA back.

For more details, you can see my full summary about "using web services from Excel."

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

Since GDB 7.5 you can use these native Convenience Functions:

$_memeq(buf1, buf2, length)
$_regex(str, regex)
$_streq(str1, str2)
$_strlen(str)

Seems quite less problematic than having to execute a "foreign" strcmp() on the process' stack each time the breakpoint is hit. This is especially true for debugging multithreaded processes.

Note your GDB needs to be compiled with Python support, which is not an issue with current linux distros. To be sure, you can check it by running show configuration inside GDB and searching for --with-python. This little oneliner does the trick, too:

$ gdb -n -quiet -batch -ex 'show configuration' | grep 'with-python'
             --with-python=/usr (relocatable)

For your demo case, the usage would be

break <where> if $_streq(x, "hello")

or, if your breakpoint already exists and you just want to add the condition to it

condition <breakpoint number> $_streq(x, "hello")

$_streq only matches the whole string, so if you want something more cunning you should use $_regex, which supports the Python regular expression syntax.

Transfer data from one HTML file to another

I use this to set Profile image on each page.

On first page set value as:

localStorage.setItem("imageurl", "ur image url");

or on second page get value as :

var imageurl=localStorage.getItem("imageurl");
document.getElementById("profilePic").src = (imageurl);

What is Android's file system?

Johan is close - it depends on the hardware manufacturer. For example, Samsung Galaxy S phones uses Samsung RFS (proprietary). However, the Nexus S (also made by Samsung) with Android 2.3 uses Ext4 (presumably because Google told them to - the Nexus S is the current Google experience phone). Many community developers have also started moving to Ext4 because of this shift.

How do I write a bash script to restart a process if it dies?

if ! test -f $PIDFILE || ! psgrep `cat $PIDFILE`; then
    restart_process
    # Write PIDFILE
    echo $! >$PIDFILE
fi

Position absolute but relative to parent

If you don't give any position to parent then by default it takes static. If you want to understand that difference refer to this example

Example 1::

http://jsfiddle.net/Cr9KB/1/

   #mainall
{

    background-color:red;
    height:150px;
    overflow:scroll
}

Here parent class has no position so element is placed according to body.

Example 2::

http://jsfiddle.net/Cr9KB/2/

#mainall
{
    position:relative;
    background-color:red;
    height:150px;
    overflow:scroll
}

In this example parent has relative position hence element are positioned absolute inside relative parent.

Calculate Age in MySQL (InnoDb)

Since the question is being tagged for mysql, I have the following implementation that works for me and I hope similar alternatives would be there for other RDBMS's. Here's the sql:

select YEAR(now()) - YEAR(dob) - ( DAYOFYEAR(now()) < DAYOFYEAR(dob) ) as age 
from table 
where ...

Use jQuery to hide a DIV when the user clicks outside of it

var n = 0;
$("#container").mouseenter(function() {
n = 0;

}).mouseleave(function() {
n = 1;
});

$("html").click(function(){ 
if (n == 1) {
alert("clickoutside");
}
});

How to add extension methods to Enums

Of course you can, say for example, you want to use the DescriptionAttribue on your enum values:

using System.ComponentModel.DataAnnotations;

public enum Duration 
{ 
    [Description("Eight hours")]
    Day,

    [Description("Five days")]
    Week,

    [Description("Twenty-one days")] 
    Month 
}

Now you want to be able to do something like:

Duration duration = Duration.Week;
var description = duration.GetDescription(); // will return "Five days"

Your extension method GetDescription() can be written as follows:

using System.ComponentModel;
using System.Reflection;

public static string GetDescription(this Enum value)
{
    FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
    if (fieldInfo == null) return null;
    var attribute = (DescriptionAttribute)fieldInfo.GetCustomAttribute(typeof(DescriptionAttribute));
    return attribute.Description;
}

Unit Testing C Code

There is CUnit

And Embedded Unit is unit testing framework for Embedded C System. Its design was copied from JUnit and CUnit and more, and then adapted somewhat for Embedded C System. Embedded Unit does not require std C libs. All objects are allocated to const area.

And Tessy automates the unit testing of embedded software.

How to check currently internet connection is available or not in android

This code to check the network availability for all versions of Android including Android 9.0 and above:

public static boolean isNetworkConnected(Context  context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
    // For 29 api or above
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
        return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) ||
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR);
    } else return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

Don't forget to add network-state permission in your manifest

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Also, add @SuppressWarnings( "deprecation" ) before the method to avoid android studio deprecation warning.

How to determine if a list of polygon points are in clockwise order?

Here's a simple Python 3 implementation based on this answer (which, in turn, is based on the solution proposed in the accepted answer)

def is_clockwise(points):
    # points is your list (or array) of 2d points.
    assert len(points) > 0
    s = 0.0
    for p1, p2 in zip(points, points[1:] + [points[0]]):
        s += (p2[0] - p1[0]) * (p2[1] + p1[1])
    return s > 0.0

How can I parse a time string containing milliseconds in it with python?

To give the code that nstehr's answer refers to (from its source):

def timeparse(t, format):
    """Parse a time string that might contain fractions of a second.

    Fractional seconds are supported using a fragile, miserable hack.
    Given a time string like '02:03:04.234234' and a format string of
    '%H:%M:%S', time.strptime() will raise a ValueError with this
    message: 'unconverted data remains: .234234'.  If %S is in the
    format string and the ValueError matches as above, a datetime
    object will be created from the part that matches and the
    microseconds in the time string.
    """
    try:
        return datetime.datetime(*time.strptime(t, format)[0:6]).time()
    except ValueError, msg:
        if "%S" in format:
            msg = str(msg)
            mat = re.match(r"unconverted data remains:"
                           " \.([0-9]{1,6})$", msg)
            if mat is not None:
                # fractional seconds are present - this is the style
                # used by datetime's isoformat() method
                frac = "." + mat.group(1)
                t = t[:-len(frac)]
                t = datetime.datetime(*time.strptime(t, format)[0:6])
                microsecond = int(float(frac)*1e6)
                return t.replace(microsecond=microsecond)
            else:
                mat = re.match(r"unconverted data remains:"
                               " \,([0-9]{3,3})$", msg)
                if mat is not None:
                    # fractional seconds are present - this is the style
                    # used by the logging module
                    frac = "." + mat.group(1)
                    t = t[:-len(frac)]
                    t = datetime.datetime(*time.strptime(t, format)[0:6])
                    microsecond = int(float(frac)*1e6)
                    return t.replace(microsecond=microsecond)

        raise

Reading output of a command into an array in Bash

Here is an example. Imagine that you are going to put the files and directory names (under the current folder) to an array and count its items. The script would be like;

my_array=( `ls` )
my_array_length=${#my_array[@]}
echo $my_array_length

Or, you can iterate over this array by adding the following script:

for element in "${my_array[@]}"
do
   echo "${element}"
done

Please note that this is the core concept and the input is considered to be sanitized before, i.e. removing extra characters, handling empty Strings, and etc. (which is out of the topic of this thread).

jQuery hasAttr checking to see if there is an attribute on an element

The best way to do this would be with filter():

$("nav>ul>li>a").filter("[data-page-id]");

It would still be nice to have .hasAttr(), but as it doesn't exist there is this way.

How can I use "e" (Euler's number) and power operation in python 2.7

You can use exp(x) function of math library, which is same as e^x. Hence you may write your code as:

import math
x.append(1 - math.exp( -0.5 * (value1*value2)**2))

I have modified the equation by replacing 1/2 as 0.5. Else for Python <2.7, we'll have to explicitly type cast the division value to float because Python round of the result of division of two int as integer. For example: 1/2 gives 0 in python 2.7 and below.

Rename multiple files based on pattern in Unix

Another possible parameter expansion:

for f in fgh*; do mv -- "$f" "jkl${f:3}"; done

Rails create or update magic?

In Rails 4 you can add to a specific model:

def self.update_or_create(attributes)
  assign_or_new(attributes).save
end

def self.assign_or_new(attributes)
  obj = first || new
  obj.assign_attributes(attributes)
  obj
end

and use it like

User.where(email: "[email protected]").update_or_create(name: "Mr A Bbb")

Or if you'd prefer to add these methods to all models put in an initializer:

module ActiveRecordExtras
  module Relation
    extend ActiveSupport::Concern

    module ClassMethods
      def update_or_create(attributes)
        assign_or_new(attributes).save
      end

      def update_or_create!(attributes)
        assign_or_new(attributes).save!
      end

      def assign_or_new(attributes)
        obj = first || new
        obj.assign_attributes(attributes)
        obj
      end
    end
  end
end

ActiveRecord::Base.send :include, ActiveRecordExtras::Relation

How to create windows service from java jar?

Use nssm.exe but remember to set the AppDirectory or any required libraries or resources will not be accessible. By default nssm set the current working directory to the that of the application, java.exe, not the jar. So do this to create a batch script:

    pushd <path-to-jar>
    nssm.exe install "<service-name>" "<path-to-java.exe>" "-jar <name-of-jar>"
    nssm.exe set "<service-name>" AppDirectory "<path-to-jar>"

This should fix the service paused issue.

How to overcome TypeError: unhashable type: 'list'

The TypeError is happening because k is a list, since it is created using a slice from another list with the line k = list[0:j]. This should probably be something like k = ' '.join(list[0:j]), so you have a string instead.

In addition to this, your if statement is incorrect as noted by Jesse's answer, which should read if k not in d or if not k in d (I prefer the latter).

You are also clearing your dictionary on each iteration since you have d = {} inside of your for loop.

Note that you should also not be using list or file as variable names, since you will be masking builtins.

Here is how I would rewrite your code:

d = {}
with open("filename.txt", "r") as input_file:
    for line in input_file:
        fields = line.split()
        j = fields.index("x")
        k = " ".join(fields[:j])
        d.setdefault(k, []).append(" ".join(fields[j+1:]))

The dict.setdefault() method above replaces the if k not in d logic from your code.

How would I access variables from one class to another?

class ClassA(object):
    def __init__(self):
        self.var1 = 1
        self.var2 = 2
    def method(self):
        self.var1 = self.var1 + self.var2
        return self.var1

class ClassB(ClassA):
    def __init__(self):
        ClassA.__init__(self)

object1 = ClassA() 
sum = object1.method()  
object2 = ClassB() 
print sum

How to wait until an element exists?

This is a simple solution for those who are used to promises and don't want to use any third party libs or timers.

I have been using it in my projects for a while

function waitForElm(selector) {
    return new Promise(resolve => {
        if (document.querySelector(selector)) {
            return resolve(document.querySelector(selector));
        }

        const observer = new MutationObserver(mutations => {
            if (document.querySelector(selector)) {
                resolve(document.querySelector(selector));
                observer.disconnect();
            }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    });
}

To use it:

waitForElm('.some-class').then(elm => console.log(elm.textContent));

or with async/await

const elm = await waitForElm('.some-classs')

The type or namespace name 'DbContext' could not be found

I had the same problem..I have VS2010 express..

(Note: If you see this problem try checking references to EntityFramework.dll .. May be it is missing.)

The following resolved it for me.

I installed latest MVC 3 Tools Update
then I installed EntityFramework 4.1
or using NUGet ie. from with Visual Studio 2010 Express (Tools->Library Package Manager -> Add library Package reference -> Select Online -> EntityFramework)

Strangely that didnt work..So i had to manually add a reference to "EntityFramework.dll"
try doing a search for the dll ..may be here
"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\"

If you already have it..just add a '.net' reference.

Note: If you use NuGet ,it creates a folder "packages" along side your Solution directory. You will find the "EntityFramework.4.1.10331.0" folder inside it.Within "Libs" folder you will find "EntityFramework.dll" .
Add reference to it using Browse tab and select the above dll.

Snap for the same

how to stop Javascript forEach?

As others have pointed out, you can't cancel a forEach loop, but here's my solution:

ary.forEach(function loop(){
    if(loop.stop){ return; }

    if(condition){ loop.stop = true; }
});

Of course this doesn't actually break the loop, it just prevents code execution on all the elements following the "break"

How to use GNU Make on Windows?

As an alternative, if you just want to install make, you can use the chocolatey package manager to install gnu make by using

choco install make -y

This deals with any path issues that you might have.