Programs & Examples On #Forcing

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

As @Ebin Joy said, If your gradle file get corrupted then there is one simple solution for that. Manually give the proxy details like shown in image. then you're good to go. This solution only works if you using any closed networks like office network etc.

enter image description here

How to enable CORS in ASP.net Core WebAPI

AspNetCoreModuleV2 cannot handle OPTIONS causing a preflight issue

I discovered that .net core module does not handle OPTIONS well which makes a big CORS problem:

Solution: remove the star *

In web.config, exclude OPTIONS verb from the module because this verb is already handled by the IIS OPTIONSVerbHandler:

 <add name="aspNetCore" path="*" verb="* modules="AspNetCoreModuleV2" resourceType="Unspecified" />

with this one

<add name="aspNetCore" path="*" verb="GET,POST,PUT,DELETE" modules="AspNetCoreModuleV2" resourceType="Unspecified" />

Cast object to interface in TypeScript

If it helps anyone, I was having an issue where I wanted to treat an object as another type with a similar interface. I attempted the following:

Didn't pass linting

const x = new Obj(a as b);

The linter was complaining that a was missing properties that existed on b. In other words, a had some properties and methods of b, but not all. To work around this, I followed VS Code's suggestion:

Passed linting and testing

const x = new Obj(a as unknown as b);

Note that if your code attempts to call one of the properties that exists on type b that is not implemented on type a, you should realize a runtime fault.

Failed to create provisioning profile

Change the bundle identifier to something more unique.

If you are following a tutorial and just put a generic identifier then adding a few numbers to the end will likely solve your issues.

i.e. if you had HelloWorld change it to HelloWorld12345

Updates were rejected because the tip of your current branch is behind its remote counterpart

the tip of your current branch is behind its remote counterpart means that there have been changes on the remote branch that you don’t have locally. and git tells you import new changes from REMOTE and merge it with your code and then push it to remote.

You can use this command to force changes to server with local repo ().

git push -f origin master

with -f tag you will override Remote Brach code with your code.

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

I had this problem (showing ERR_INCOMPLETE_CHUNKED_ENCODING in Chrome, nothing in other browsers). Turned out the problem was my hosting provider GoDaddy adding a monitoring script at the end of my output.

https://www.godaddy.com/community/cPanel-Hosting/how-to-remove-additional-quot-monitoring-quot-script-added/td-p/62592

Google Chrome forcing download of "f.txt" file

FYI, after reading this thread, I took a look at my installed programs and found that somehow, shortly after upgrading to Windows 10 (possibly/probably? unrelated), an ASK search app was installed as well as a Chrome extension (Windows was kind enough to remind to check that). Since removing, I have not have the f.txt issue.

How to mount host volumes into docker containers in Dockerfile during build

If you are looking for a way to "mount" files, like -v for docker run, you can now use the --secret flag for docker build

echo 'WARMACHINEROX' > mysecret.txt
docker build --secret id=mysecret,src=mysecret.txt .

And inside your Dockerfile you can now access this secret

# syntax = docker/dockerfile:1.0-experimental
FROM alpine

# shows secret from default secret location:
RUN --mount=type=secret,id=mysecret cat /run/secrets/mysecret

# shows secret from custom secret location:
RUN --mount=type=secret,id=mysecret,dst=/foobar cat /foobar

More in-depth information about --secret available on Docker Docs

Laravel - display a PDF file in storage without forcing download?

Retrieve File name first then in Blade file use anchor(a) tag like below shown. This would works for image view also.

<a href="{{ asset('storage/admission-document-uploads/' . $filename) }}" target="_black"> view Pdf </a>;

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

I also faced the above error. I used Eclipse.

After followed the below solution, it works fine for me.

Solution is,

  1. Right click project "pom.xml" in eclipse and select Maven Install.
  2. Right click on the project -> Maven -> Update Project.
  3. Refresh

Suppress warning messages using mysql from within Terminal, but password written in bash script

Personally, I use script wrapper to catch that error. Here is code sample:

#!/bin/bash

#echo $@ | cat >> /home/mysqldump.log 2>/dev/null
ERR_FILE=/tmp/tmp_mdump.err

# Execute dumper
/usr/bin/mysqldump $@ 2>$ERR_FILE

# Determine error and remove tmp file
ERROR=`cat $ERR_FILE`
rm $ERR_FILE

# Handle an error
if [ "" != "$ERROR" ]; then

        # Error occured
        if [ "Warning: Using a password on the command line interface can be insecure." != "$ERROR" ]; then
                echo $ERROR >&2
                exit 1
        fi
fi

Concrete Javascript Regex for Accented Characters (Diacritics)

from this wiki : https://en.wikipedia.org/wiki/List_of_Unicode_characters#Basic_Latin

for latin letters, I use

/^[A-zÀ-ÖØ-öø-ÿ]+$/ 

it avoids hyphens and specials chars

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

add this to your stylesheet. line-height should match the height of your logo

.navbar-nav li a {
 line-height: 50px;
}

Check out the fiddle at: http://jsfiddle.net/nD4tW/

iOS 7: UITableView shows under status bar

Abrahamchez's solution https://developer.apple.com/library/ios/qa/qa1797/_index.html worked for me as follows. I had a single UITableviewcontroller as my initial view. I had tried the offset code and embedding in a navcon but neither solved the statusbar transparency.

Add a Viewcontroller and make it the initial view. This should show you critical Top & Bottom Layout Guides.

Drag the old Tableview into the View in the new controller.

Do all the stuff to retrofit the table into the new controller:

Change your old view controller.h file to inherit/subclass from UIViewController instead of UITableViewController.

Add UITableViewDataSource and UITableViewDelegate to the viewcontroller's .h.

Re-connect anything needed in the storyboard, such as a Searchbar.

The big thing is to get the constraints set up, as in the Apple Q&A. I didn't bother inserting a toolbar. Not certain the exact sequence. But a red icon appeared on the Layout Guides, perhaps when I built. I clicked it and let Xcode install/clean up the constraints.

Then I clicked everywhere until I found the Vertical Space constraint and changed its top value from -20 to 0 and it worked perfectly.

Automatic prune with Git fetch or pull

Since git 1.8.5 (Q4 2013):

"git fetch" (hence "git pull" as well) learned to check "fetch.prune" and "remote.*.prune" configuration variables and to behave as if the "--prune" command line option was given.

That means that, if you set remote.origin.prune to true:

git config remote.origin.prune true

Any git fetch or git pull will automatically prune.

Note: Git 2.12 (Q1 2017) will fix a bug related to this configuration, which would make git remote rename misbehave.
See "How do I rename a git remote?".


See more at commit 737c5a9:

Without "git fetch --prune", remote-tracking branches for a branch the other side already has removed will stay forever.
Some people want to always run "git fetch --prune".

To accommodate users who want to either prune always or when fetching from a particular remote, add two new configuration variables "fetch.prune" and "remote.<name>.prune":

  • "fetch.prune" allows to enable prune for all fetch operations.
  • "remote.<name>.prune" allows to change the behaviour per remote.

The latter will naturally override the former, and the --[no-]prune option from the command line will override the configured default.

Since --prune is a potentially destructive operation (Git doesn't keep reflogs for deleted references yet), we don't want to prune without users consent, so this configuration will not be on by default.

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

Caching a jquery ajax response in javascript/browser

I was looking for caching for my phonegap app storage and I found the answer of @TecHunter which is great but done using localCache.

I found and come to know that localStorage is another alternative to cache the data returned by ajax call. So, I created one demo using localStorage which will help others who may want to use localStorage instead of localCache for caching.

Ajax Call:

$.ajax({
    type: "POST",
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    url: url,
    data: '{"Id":"' + Id + '"}',
    cache: true, //It must "true" if you want to cache else "false"
    //async: false,
    success: function (data) {
        var resData = JSON.parse(data);
        var Info = resData.Info;
        if (Info) {
            customerName = Info.FirstName;
        }
    },
    error: function (xhr, textStatus, error) {
        alert("Error Happened!");
    }
});

To store data into localStorage:

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (options.cache) {
    var success = originalOptions.success || $.noop,
        url = originalOptions.url;

    options.cache = false; //remove jQuery cache as we have our own localStorage
    options.beforeSend = function () {
        if (localStorage.getItem(url)) {
            success(localStorage.getItem(url));
            return false;
        }
        return true;
    };
    options.success = function (data, textStatus) {
        var responseData = JSON.stringify(data.responseJSON);
        localStorage.setItem(url, responseData);
        if ($.isFunction(success)) success(responseJSON); //call back to original ajax call
    };
}
});

If you want to remove localStorage, use following statement wherever you want:

localStorage.removeItem("Info");

Hope it helps others!

Node.js res.setHeader('content-type', 'text/javascript'); pushing the response javascript as file download

Use application/javascript as content type instead of text/javascript

text/javascript is mentioned obsolete. See reference docs.

http://www.iana.org/assignments/media-types/application

Also see this question on SO.

UPDATE:

I have tried executing the code you have given and the below didn't work.

res.setHeader('content-type', 'text/javascript');
res.send(JS_Script);

This is what worked for me.

res.setHeader('content-type', 'text/javascript');
res.end(JS_Script);

As robertklep has suggested, please refer to the node http docs, there is no response.send() there.

Fixed header table with horizontal scrollbar and vertical scrollbar on

The solution is to use JS to horizontally scroll the top div so that it matches the bottom div.

You must be very careful to make sure the top and bottom are exactly the same sizes, for example you might need to make the TD and TH use fixed widths.

Here is a fiddle https://jsfiddle.net/jdhenckel/yzjhk08h/5/

The important parts: CSS use

.head {
  overflow-x: hidden;
  overflow-y: scroll;
  width: 500px;
}
.lower {
  overflow-x: auto;
  overflow-y: scroll;
  width: 500px;
  height: 400px;
}

Notice overflow-y must be the same on both head and lower.

And the Javascript...

var head = document.querySelector('.head');

var lower = document.querySelector('.lower');

lower.addEventListener('scroll', function (e) {
  console.log(lower.scrollLeft);
  head.scrollLeft = lower.scrollLeft;
});

making matplotlib scatter plots from dataframes in Python's pandas

There is little to be added to Garrett's great answer, but pandas also has a scatter method. Using that, it's as easy as

df = pd.DataFrame(np.random.randn(10,2), columns=['col1','col2'])
df['col3'] = np.arange(len(df))**2 * 100 + 100
df.plot.scatter('col1', 'col2', df['col3'])

plotting sizes in col3 to col1-col2

htaccess redirect to https://www

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R]

Enforcing the type of the indexed members of a Typescript object?

Define interface

interface Settings {
  lang: 'en' | 'da';
  welcome: boolean;
}

Enforce key to be a specific key of Settings interface

private setSettings(key: keyof Settings, value: any) {
   // Update settings key
}

Forcing Internet Explorer 9 to use standards document mode

Make sure you use the right doctype.

eg.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

or just

<!doctype html>

and also read and understand how compatibility modes and developer toolbar for IE work and set modes for IE:

HTML Mobile -forcing the soft keyboard to hide

example how i made it , After i fill a Maximum length it will blur from my Field (and the Keyboard will disappear ) , if you have more than one field , you can just add the line that i add '//'

var MaxLength = 8;
    $(document).ready(function () {
        $('#MyTB').keyup(function () {
            if ($(this).val().length >= MaxLength) {
               $('#MyTB').blur();
             //  $('#MyTB2').focus();
         }
          }); });

Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, reason: Connection to https://dl-ssl.google.com refused

Go to Internet Explorer, into options -> connections -> Lan settings. There should be an automatic config script option, copy the url, paste it into a browser, this downloads the config file, opened the file up in notepad and there will be a proxy address and a port number in there like 192.234.10.23:88 paste the address into the proxy field and the port (88) into the port field in the Android SDK manager Tools -> Options dialog.

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

One contending technology you've omitted is Server-Sent Events / Event Source. What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet? has a good discussion of all of these. Keep in mind that some of these are easier than others to integrate with on the server side.

python date of the previous month

Building off the comment of @J.F. Sebastian, you can chain the replace() function to go back one "month". Since a month is not a constant time period, this solution tries to go back to the same date the previous month, which of course does not work for all months. In such a case, this algorithm defaults to the last day of the prior month.

from datetime import datetime, timedelta

d = datetime(2012, 3, 31) # A problem date as an example

# last day of last month
one_month_ago = (d.replace(day=1) - timedelta(days=1))
try:
    # try to go back to same day last month
    one_month_ago = one_month_ago.replace(day=d.day)
except ValueError:
    pass
print("one_month_ago: {0}".format(one_month_ago))

Output:

one_month_ago: 2012-02-29 00:00:00

Contain an image within a div?

Use max width and max height. It will keep the aspect ratio

#container img 
{
 max-width: 250px;
 max-height: 250px;
}

http://jsfiddle.net/rV77g/

forcing web-site to show in landscape mode only

I had to play with the widths of my main containers:

html {
  @media only screen and (orientation: portrait) and (max-width: 555px) {
    transform: rotate(90deg);
    width: calc(155%);
    .content {
      width: calc(155%);
    }
  }
}

Forcing a postback

No, not from code behind. A postback is a request initiated from a page on the client back to itself on the server using the Http POST method. On the server side you can request a redirect but the will be Http GET request.

Set position / size of UI element as percentage of screen size

Take a look at this:

http://developer.android.com/reference/android/util/DisplayMetrics.html

You can get the heigth of the screen and it's simple math to calculate 68 percent of the screen.

PHP header(Location: ...): Force URL change in address bar

use

header("Location: index.php"); //this work in my site

read more on header() at php documentation.

css transform, jagged edges in chrome

You might be able to mask the jagging using blurred box-shadows. Using -webkit-box-shadow instead of box-shadow will make sure it doesn't affect non-webkit browsers. You might want to check Safari and the mobile webkit browsers though.

The result is somewhat better, but still a lot less good then with the other browsers:

with box shadow (underside)

org.hibernate.PersistentObjectException: detached entity passed to persist

Here you have used native and assigning value to the primary key, in native primary key is auto generated.

Hence the issue is coming.

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

Even if you have unchecked the "Display intranet sites in Compatibility View" option, and have the X-UA-Compatible in your response headers, there is another reason why your browser might default to "Compatibility View" anyways - your Group Policy. Look at your console for the following message:

HTML1203: xxx.xxx has been configured to run in Compatibility View through Group Policy.

Where xxx.xxx is the domain for your site (i.e. test.com). If you see this then the group policy for your domain is set so that any site ending in test.com will automatically render in Compatibility mode regardless of doctype, headers, etc.

For more information, please see the following link (explains the html codes): http://msdn.microsoft.com/en-us/library/ie/hh180764(v=vs.85).aspx

How do I properly force a Git push?

Just do:

git push origin <your_branch_name> --force

or if you have a specific repo:

git push https://git.... --force

This will delete your previous commit(s) and push your current one.

It may not be proper, but if anyone stumbles upon this page, thought they might want a simple solution...

Short flag

Also note that -f is short for --force, so

git push origin <your_branch_name> -f

will also work.

CSS to line break before/after a particular `inline-block` item

I accomplished this by creating a ::before selector for the first inline element in the row, and making that selector a block with a top or bottom margin to separate rows a little bit.

.1st_item::before
{
  content:"";
  display:block;
  margin-top: 5px;
}

.1st_item
{
  color:orange;
  font-weight: bold;
  margin-right: 1em;
}

.2nd_item
{
  color: blue;
}

Forcing label to flow inline with input that they label

<style>
.nowrap {
    white-space: nowrap;
}
</style>

...

<label for="id1" class="nowrap">label1:
    <input type="text" id="id1"/>
</label>

Wrap your inputs within the label tag

Matplotlib/pyplot: How to enforce axis range?

Try putting the call to axis after all plotting commands.

WebView and HTML5 <video>

Well, apparently this is just not possible without using a JNI to register a plugin to get the video event. (Personally, I am avoiding JNI's since I really don't want to deal with a mess when Atom-based android tablets come out in the next few months, losing the portability of Java.)

The only real alternative seems to be to create a new web page just for WebView and do video the old-school way with an A HREF link as cited in the Codelark url above.

Icky.

git stash blunder: git stash pop and ended up with merge conflicts

Note that Git 2.5 (Q2 2015) a future Git might try to make that scenario impossible.

See commit ed178ef by Jeff King (peff), 22 Apr 2015.
(Merged by Junio C Hamano -- gitster -- in commit 05c3967, 19 May 2015)

Note: This has been reverted. See below.

stash: require a clean index to apply/pop

Problem

If you have staged contents in your index and run "stash apply/pop", we may hit a conflict and put new entries into the index.
Recovering to your original state is difficult at that point, because tools like "git reset --keep" will blow away anything staged.

In other words:

"git stash pop/apply" forgot to make sure that not just the working tree is clean but also the index is clean.
The latter is important as a stash application can conflict and the index will be used for conflict resolution.

Solution

We can make this safer by refusing to apply when there are staged changes.

That means if there were merges before because of applying a stash on modified files (added but not committed), now they would not be any merges because the stash apply/pop would stop immediately with:

Cannot apply stash: Your index contains uncommitted changes.

Forcing you to commit the changes means that, in case of merges, you can easily restore the initial state( before git stash apply/pop) with a git reset --hard.


See commit 1937610 (15 Jun 2015), and commit ed178ef (22 Apr 2015) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit bfb539b, 24 Jun 2015)

That commit was an attempt to improve the safety of applying a stash, because the application process may create conflicted index entries, after which it is hard to restore the original index state.

Unfortunately, this hurts some common workflows around "git stash -k", like:

git add -p       ;# (1) stage set of proposed changes
git stash -k     ;# (2) get rid of everything else
make test        ;# (3) make sure proposal is reasonable
git stash apply  ;# (4) restore original working tree

If you "git commit" between steps (3) and (4), then this just works. However, if these steps are part of a pre-commit hook, you don't have that opportunity (you have to restore the original state regardless of whether the tests passed or failed).

How do I force git to use LF instead of CR+LF under windows?

The proper way to get LF endings in Windows is to first set core.autocrlf to false:

git config --global core.autocrlf false

You need to do this if you are using msysgit, because it sets it to true in its system settings.

Now git won’t do any line ending normalization. If you want files you check in to be normalized, do this: Set text=auto in your .gitattributes for all files:

* text=auto

And set core.eol to lf:

git config --global core.eol lf

Now you can also switch single repos to crlf (in the working directory!) by running

git config core.eol crlf

After you have done the configuration, you might want git to normalize all the files in the repo. To do this, go to to the root of your repo and run these commands:

git rm --cached -rf .
git diff --cached --name-only -z | xargs -n 50 -0 git add -f

If you now want git to also normalize the files in your working directory, run these commands:

git ls-files -z | xargs -0 rm
git checkout .

Why is it bad practice to call System.gc()?

The reason everyone always says to avoid System.gc() is that it is a pretty good indicator of fundamentally broken code. Any code that depends on it for correctness is certainly broken; any that rely on it for performance are most likely broken.

You don't know what sort of garbage collector you are running under. There are certainly some that do not "stop the world" as you assert, but some JVMs aren't that smart or for various reasons (perhaps they are on a phone?) don't do it. You don't know what it's going to do.

Also, it's not guaranteed to do anything. The JVM may just entirely ignore your request.

The combination of "you don't know what it will do," "you don't know if it will even help," and "you shouldn't need to call it anyway" are why people are so forceful in saying that generally you shouldn't call it. I think it's a case of "if you need to ask whether you should be using this, you shouldn't"


EDIT to address a few concerns from the other thread:

After reading the thread you linked, there's a few more things I'd like to point out. First, someone suggested that calling gc() may return memory to the system. That's certainly not necessarily true - the Java heap itself grows independently of Java allocations.

As in, the JVM will hold memory (many tens of megabytes) and grow the heap as necessary. It doesn't necessarily return that memory to the system even when you free Java objects; it is perfectly free to hold on to the allocated memory to use for future Java allocations.

To show that it's possible that System.gc() does nothing, view:

http://bugs.sun.com/view_bug.do?bug_id=6668279

and in particular that there's a -XX:DisableExplicitGC VM option.

Curl setting Content-Type incorrectly

I think you want to specify

-H "Content-Type:text/xml"

with a colon, not an equals.

What is the most robust way to force a UIView to redraw?

I had the same problem, and all the solutions from SO or Google didn't work for me. Usually, setNeedsDisplay does work, but when it doesn't...
I've tried calling setNeedsDisplay of the view just every possible way from every possible threads and stuff - still no success. We know, as Rob said, that

"this needs to be drawn in the next draw cycle."

But for some reason it wouldn't draw this time. And the only solution I've found is calling it manually after some time, to let anything that blocks the draw pass away, like this:

dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 
                                        (int64_t)(0.005 * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
    [viewToRefresh setNeedsDisplay];
});

It's a good solution if you don't need the view to redraw really often. Otherwise, if you're doing some moving (action) stuff, there is usually no problems with just calling setNeedsDisplay.

I hope it will help someone who is lost there, like I was.

Forcing to download a file using PHP

A previous answer on this page describes how to use .htaccess to force all files of a certain type to download. However, the solution does not work with all file types across all browsers. This is a more reliable way:

<FilesMatch "\.(?i:csv)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

You might need to flush your browser cache to see this working correctly.

Strange problem with Subversion - "File already exists" when trying to recreate a directory that USED to be in my repository

I had a problem like this when I deleted a folder (and sub-folders) and went to recreate them from scratch. You get this error from manually deleting and re-adding folders (whereas files seem to cope OK with this).

After some frustrating messing around, found I had to:
(using TortoiseSVN on Windows)

  1. Move conflicting folders out of working copy (so that I don't lose my work-in-progress)
  2. Do an svn update which added old files/folders back into working copy
  3. svn delete folder
  4. commit
  5. Copy new folder back into working copy (ensuring you delete all the .svn folders inside)
  6. commit

Unfortunately it (A) requires two commits, and (B) loses file revision history as it only tracks back to the recent re-add (unless someone can explain how to fix this). An alternative solution that works around these 2 issues is to skip steps 3 and 4, the only problem being that old/unnecessary files may still be present in your directory. You could delete these manually.

Would love to hear any additional insights others might have on this.

Simon.


[Update] OK, I had this same problem again just then, but the offending folder was NOT in the last commit, so an update didn't restore it. Instead I had to browse the repository and delete the offending folder. I could then add the folder back in and commit successfully.

Forcing anti-aliasing using css: Is this a myth?

I found a really awkward solution using the zoom and filter ms-only properties Example (try with no aa, standard and cleartype): http://nadycoon.hu/special/archive/internet-explorer-force-antialias.html

How it works:

-zoom up text with zoom:x, x>1

-apply some blur(s) (or any other filter)

-zoom down with zoom:1/x

It's a bit slow, and very! memory-hungry method, and on non-white backgrounds it has some slight dark halo.

CSS:

.insane-aa-4b                  { zoom:0.25; }
.insane-aa-4b .insane-aa-inner { zoom:4; }
.insane-aa-4b .insane-aa-blur  { zoom:1;
  filter:progid:DXImageTransform.Microsoft.Blur(pixelRadius=2);
}

HTML:

<div class="insane-aa-4b">
<div class="insane-aa-blur">
<div class="insane-aa-inner">
  <div style="font-size:12px;">Lorem Ipsum</div>
</div></div></div>

You can use this short jQuery to force anti-aliasing, just add the ieaa class to anything:

$(function(){ $('.ieaa').wrap(
'<div style="zoom:0.25;"><div style="zoom:1;filter:progid:DXImageTransform.Microsoft.Blur(pixelRadius=2);"><div style="zoom:4;"><'+'/div><'+'/div><'+'/div>'
); });

SSIS Excel Import Forcing Incorrect Column Type

I was banging my head against a wall with this issue for a while. In our environment, we consume price files from our suppliers in various formats, some of which have upward of a million records. This issue usually occurs where:

  • The rows scanned by the OLEDB driver appear to contain numbers, but do contain mixed values later on in the record set, or
  • Fields do contain only numbers, but the source has some formatted as text (usually Excel files).

The problem is that even if you set your external input column to the desired data type, the file gets scanned every time you run the package and is dynamically changed to whatever the OLEDB driver thinks the field should be.

Our source files typically contain field headers (text) and prices (numeric fields), which gives me an easy solution:

First step:

  • Change your SQL statement to include the header fields. This forces SSIS to see all fields as text, including the price fields.

For mixed fields:

  • Your initial problem is solved because your fields are now text, but you still have a header row in your output.
  • Prevent the header row from making it into your output by changing the SQL WHERE clause to exclude the header values e.g. "WHERE NOT([F4]='Price')"

For numeric fields:

  • Using the advanced editor for the OLE DB source, set the output column for the price field (or any other numeric field) to a numeric DataType. This causes any records that contain text in these fields to fail, including the header record, but forces a conversion on numeric values saved as text.

  • Set the Error Output to ignore failures on your numeric fields.

  • Alternatively, if you still need any errors on the numeric fields redirected, remove the header row by changing the SQL WHERE clause to exclude the header values then,

  • Set the Error Output to redirect failures on this field.

Obviously this method only works where you have header fields, but hopefully this helps some of you.

Why should I use the keyword "final" on a method parameter in Java?

Sometimes it's nice to be explicit (for readability) that the variable doesn't change. Here's a simple example where using final can save some possible headaches:

public void setTest(String test) {
    test = test;
}

If you forget the 'this' keyword on a setter, then the variable you want to set doesn't get set. However, if you used the final keyword on the parameter, then the bug would be caught at compile time.

Table cell widths - fixing width, wrapping/truncating long words

As long as you fix the width of the table itself and set the table-layout property, this is pretty simple :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <style type="text/css">
        td { width: 30px; overflow: hidden; }
        table { width : 90px; table-layout: fixed; }
    </style>
</head>
<body>

    <table border="2">
        <tr>
            <td>word</td>
            <td>two words</td>
            <td>onereallylongword</td>

        </tr>
    </table>
</body>
</html>

I've tested this in IE6 and 7 and it seems to work fine.

SQL Server: Query fast, but slow from procedure

I've got another idea. What if you create this table-based function:

CREATE FUNCTION tbfSelectFromView
(   
    -- Add the parameters for the function here
    @SessionGUID UNIQUEIDENTIFIER
)
RETURNS TABLE 
AS
RETURN 
(
    SELECT *
    FROM Report_Opener
    WHERE SessionGUID = @SessionGUID
    ORDER BY CurrencyTypeOrder, Rank
)
GO

And then selected from it using the following statement (even putting this in your SP):

SELECT *
FROM tbfSelectFromView(@SessionGUID)

It looks like what's happening (which everybody has already commented on) is that SQL Server just makes an assumption somewhere that's wrong, and maybe this will force it to correct the assumption. I hate to add the extra step, but I'm not sure what else might be causing it.

How to properly and completely close/reset a TcpClient connection?

You have to close the stream before closing the connection:

tcpClient.GetStream().Close();
tcpClient.Close();

Closing the client does not close the stream.

How do you check if a JavaScript Object is a DOM Object?

The following IE8 compatible, super-simple code works perfectly.

The accepted answer does not detect all types of HTML elements. For example, SVG elements are not supported. In contrast, this answer works for HTML well as SVG.

See it in action here: https://jsfiddle.net/eLuhbu6r/

function isElement(element) {
    return element instanceof Element || element instanceof HTMLDocument;  
}

Best Practice for Forcing Garbage Collection in C#

Not sure if it is a best practice, but when working with large amounts of images in a loop (i.e. creating and disposing a lot of Graphics/Image/Bitmap objects), i regularly let the GC.Collect.

I think I read somewhere that the GC only runs when the program is (mostly) idle, and not in the middle of a intensive loop, so that could look like an area where manual GC could make sense.

How to manage a redirect request after a jQuery Ajax call

I just wanted to latch on to any ajax requests for the entire page. @SuperG got me started. Here is what I ended up with:

// redirect ajax requests that are redirected, not found (404), or forbidden (403.)
$('body').bind('ajaxComplete', function(event,request,settings){
        switch(request.status) {
            case 301: case 404: case 403:                    
                window.location.replace("http://mysite.tld/login");
                break;
        }
});

I wanted to specifically check for certain http status codes to base my decision on. However, you can just bind to ajaxError to get anything other than success (200 only perhaps?) I could have just written:

$('body').bind('ajaxError', function(event,request,settings){
    window.location.replace("http://mysite.tld/login");
}

What should I do when 'svn cleanup' fails?

I ran into that too lately. The trick for me was after selecting "Clean up", in the popup options dialog, check "Break Locks", and then "OK". It cleaned up successfully for me.

Microsoft Excel mangles Diacritics in .csv files?

As Fregal said \uFEFF is the way to go.

<%@LANGUAGE="JAVASCRIPT" CODEPAGE="65001"%>
<%
Response.Clear();
Response.ContentType = "text/csv";
Response.Charset = "utf-8";
Response.AddHeader("Content-Disposition", "attachment; filename=excelTest.csv");
Response.Write("\uFEFF");
// csv text here
%>

How to force the browser to reload cached CSS and JavaScript files

You could simply add some random number with the CSS and JavaScript URL like

example.css?randomNo = Math.random()

How do I kill a VMware virtual machine that won't die?

Similar, but using WMIC command line to obtain the process ID and path:

WMIC /OUTPUT:C:\ProcessList.txt PROCESS get Caption,Commandline,Processid

This will create a text file with each process and its parameters. You can search in the file for your VM File Path, and get the correct Process ID to end task with.

Thanks to http://windowsxp.mvps.org/listproc.htm for the correct command line parameters.

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

I had two problems... outdated AJAXControlkit - deleted the old dll, removed old controls from toolbox, downloaded new version, loaded toolbox, and dragged and dropped new controls on the page (see http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Studio_.NET_2005/Q_24591597.html)

Also had misspelling in my label control (had used 'class' instead of 'cssclass').

Ta

What is the LD_PRELOAD trick?

when LD_PRELOAD is used that file will be loaded before any other $export LD_PRELOAD=/path/lib lib to be pre loaded, even this can be used in programs too

How to get on scroll events?

You could use a @HostListener decorator. Works with Angular 4 and up.

import { HostListener } from '@angular/core';

@HostListener("window:scroll", []) onWindowScroll() {
    // do some stuff here when the window is scrolled
    const verticalOffset = window.pageYOffset 
          || document.documentElement.scrollTop 
          || document.body.scrollTop || 0;
}

Factorial in numpy and scipy

The answer for Ashwini is great, in pointing out that scipy.math.factorial, numpy.math.factorial, math.factorial are the same functions. However, I'd recommend use the one that Janne mentioned, that scipy.special.factorial is different. The one from scipy can take np.ndarray as an input, while the others can't.

In [12]: import scipy.special

In [13]: temp = np.arange(10) # temp is an np.ndarray

In [14]: math.factorial(temp) # This won't work
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-039ec0734458> in <module>()
----> 1 math.factorial(temp)

TypeError: only length-1 arrays can be converted to Python scalars

In [15]: scipy.special.factorial(temp) # This works!
Out[15]: 
array([  1.00000000e+00,   1.00000000e+00,   2.00000000e+00,
         6.00000000e+00,   2.40000000e+01,   1.20000000e+02,
         7.20000000e+02,   5.04000000e+03,   4.03200000e+04,
         3.62880000e+05])

So, if you are doing factorial to a np.ndarray, the one from scipy will be easier to code and faster than doing the for-loops.

SQL split values to multiple rows

CREATE PROCEDURE `getVal`()
BEGIN
        declare r_len integer;
        declare r_id integer;
        declare r_val varchar(20);
        declare i integer;
        DECLARE found_row int(10);
        DECLARE row CURSOR FOR select length(replace(val,"|","")),id,val from split;
        create table x(id int,name varchar(20));
      open row;
            select FOUND_ROWS() into found_row ;
            read_loop: LOOP
                IF found_row = 0 THEN
                         LEAVE read_loop;
                END IF;
            set i = 1;  
            FETCH row INTO r_len,r_id,r_val;
            label1: LOOP        
                IF i <= r_len THEN
                  insert into x values( r_id,SUBSTRING(replace(r_val,"|",""),i,1));
                  SET i = i + 1;
                  ITERATE label1;
                END IF;
                LEAVE label1;
            END LOOP label1;
            set found_row = found_row - 1;
            END LOOP;
        close row;
        select * from x;
        drop table x;
END

Is it possible to use JavaScript to change the meta-tags of the page?

If we don't have the meta tag at all, then we can use the following:

var _desc = 'Out description';
var meta = document.createElement('meta');
meta.setAttribute('name', 'description');
meta.setAttribute('content', _desc);
document.getElementsByTagName('head')[0].appendChild(meta);

How to show hidden divs on mouseover?

Pass the mouse over the container and go hovering on the divs I use this for jQuery DropDown menus mainly:

Copy the whole document and create a .html file you'll be able to figure out on your own from that!

            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
            <html xmlns="http://www.w3.org/1999/xhtml">
            <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <title>The Divs Case</title>
            <style type="text/css">
            * {margin:0px auto;
            padding:0px;}

            .container {width:800px;
            height:600px;
            background:#FFC;
            border:solid #F3F3F3 1px;}

            .div01 {float:right;
            background:#000;
            height:200px;
            width:200px;
            display:none;}

            .div02 {float:right;
            background:#FF0;
            height:150px;
            width:150px;
            display:none;}

            .div03 {float:right;
            background:#FFF;
            height:100px;
            width:100px;
            display:none;}

            div.container:hover div.div01 {display:block;}
            div.container div.div01:hover div.div02  {display:block;}
            div.container div.div01 div.div02:hover div.div03 {display:block;}

            </style>
            </head>
            <body>

            <div class="container">
              <div class="div01">
                <div class="div02">
                    <div class="div03">
                    </div>
                </div>
              </div>

            </div>
            </body>
            </html>

How to define a variable in a Dockerfile?

You can use ARG - see https://docs.docker.com/engine/reference/builder/#arg

The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag. If a user specifies a build argument that was not defined in the Dockerfile, the build outputs an error.

iOS: Modal ViewController with transparent background

The Login screen is a modal, meaning that it sits on top of the previous screen. So far we have Blurred Background, but it’s not blurring anything; it’s just a grey background.

We need to set our Modal properly.

image link target

  • First, we need to change the View Controller’s View background to Clear color. It simply means that it should be transparent. By default, that View is white.

  • Second, we need to select the Segue that leads to the Login screen, and in the Attribute Inspector, set the Presentation to Over Current Context. This option is only available with Auto Layout and Size Classes enabled.

image link target

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

A more hacky way is to add eg., in boot.tsx the line

import './path/declare_modules.d.ts';

with

declare module 'react-materialize';
declare module 'react-router';
declare module 'flux';

in declare_modules.d.ts

It works but other solutions are better IMO.

How to cd into a directory with space in the name?

$ DOCS="/cygdrive/c/Users/my\ dir/Documents"

Here's your first problem. This puts an actual backslash character into $DOCS, as you can see by running this command:

$ echo "$DOCS"
/cygdrive/c/Users/my\ `

When defining DOCS, you do need to escape the space character. You can quote the string (using either single or double quotes) or you can escape just the space character with a backslash. You can't do both. (On most Unix-like systems, you can have a backslash in a file or directory name, though it's not a good idea. On Cygwin or Windows, \ is a directory delimiter. But I'm going to assume the actual name of the directory is my dir, not my\ dir.)

$ cd $DOCS

This passes two arguments to cd. The first is cygdrive/c/Users/my\, and the second is dir/Documents. It happens that cd quietly ignores all but its first argument, which explains the error message:

-bash: cd: /cygdrive/c/Users/my\: No such file or directory

To set $DOCS to the name of your Documents directory, do any one of these:

$ DOCS="/cygdrive/c/Users/my dir/Documents"
$ DOCS='/cygdrive/c/Users/my dir/Documents'
$ DOCS=/cygdrive/c/Users/my\ dir/Documents

Once you've done that, to change to your Documents directory, enclose the variable reference in double quotes (that's a good idea for any variable reference in bash, unless you're sure the value doesn't have any funny characters):

$ cd "$DOCS"

You might also consider giving that directory a name without any spaces in it -- though that can be hard to do in general on Windows.

What is the pythonic way to unpack tuples?

Generally, you can use the func(*tuple) syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:

t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(*t[0:7])

This is called unpacking a tuple, and can be used for other iterables (such as lists) too. Here's another example (from the Python tutorial):

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

How to open adb and use it to send commands

If you have downloaded the AS + SDK bundle: in Windows 10

C:\Users\ your User Name \AppData\Local\Android\sdk\platform-tools\

Run adb.exe

Type adb shell.

Now able to access adb and the db.

How to find Control in TemplateField of GridView?

If your GridView is databond, make an index column in the resultset you retrive like this:

select row_number() over(order by YourIdentityColumn asc)-1 as RowIndex, * from YourTable where [Expresion]

In the command control you want to use make the value of CommandArgument property equal to the row index of the DataSet table RowIndex like this:

<asp:LinkButton ID="lbnMsgSubj" runat="server" Text='<%# Eval("MsgSubj") %>' Font-Underline="false" CommandArgument='<%#Eval("RowIndex") %>' />

Use the OnRowCommand event to fire on clicking the link button like this:

<asp:GridView ID="gvwStuMsgBoard" runat="server" AutoGenerateColumns="false" GridLines="Horizontal" BorderColor="Transparent" Width="100%" OnRowCommand="gvwStuMsgBoard_RowCommand">

Finally the code behind you can then do whatever you like when the event is triggered like this:

protected void gvwStuMsgBoard_RowCommand(object sender, GridViewCommandEventArgs e)
{
    Panel pnlMsgBody = (Panel)gvwStuMsgBoard.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("pnlMsgBody");
    if(pnlMsgBody.Visible == false)
    {
        pnlMsgBody.Visible = true;
    }
    else
    {
        pnlMsgBody.Visible = false;
    }
}

Add User to Role ASP.NET Identity

Below is an alternative implementation of a 'create user' controller method using Claims based roles.

The created claims then work with the Authorize attribute e.g. [Authorize(Roles = "Admin, User.*, User.Create")]

    // POST api/User/Create
    [Route("Create")]
    public async Task<IHttpActionResult> Create([FromBody]CreateUserModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        // Generate long password for the user
        var password = System.Web.Security.Membership.GeneratePassword(25, 5);

        // Create the user
        var user = new ApiUser() { UserName = model.UserName };
        var result = await UserManager.CreateAsync(user, password);
        if (!result.Succeeded)
        {
            return GetErrorResult(result);
        }

        // Add roles (permissions) for the user
        foreach (var perm in model.Permissions)
        {
            await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, perm));
        }

        return Ok<object>(new { UserName = user.UserName, Password = password });
    }

DataTables fixed headers misaligned with columns in wide tables

I am having the same issue on IE9.

I will just use a RegExp to strip all the white spaces before writing the HTML to the page.

var Tables=$('##table_ID').html();
var expr = new RegExp('>[ \t\r\n\v\f]*<', 'g');
Tables= Tables.replace(expr, '><');
$('##table_ID').html(Tables);
oTable = $('##table_ID').dataTable( {
  "bPaginate": false,
  "bLengthChange": false,
  "bFilter": false,
  "bSort": true,
  "bInfo": true,
  "bAutoWidth": false,
  "sScrollY": ($(window).height() - 320),
  "sScrollX": "100%",
  "iDisplayLength":-1,
  "sDom": 'rt<"bottom"i flp>'
} );

Enable/Disable a dropdownbox in jquery

I am using JQuery > 1.8 and this works for me...

$('#dropDownId').attr('disabled', true);

How to get the full url in Express?

Instead of concatenating the things together on your own, you could instead use the node.js API for URLs and pass URL.format() the informations from express.

Example:

var url = require('url');

function fullUrl(req) {
  return url.format({
    protocol: req.protocol,
    host: req.get('host'),
    pathname: req.originalUrl
  });
}

How can I remove the outline around hyperlinks images?

For Remove outline for anchor tag

a {outline : none;}

Remove outline from image link

a img {outline : none;}

Remove border from image link

img {border : 0;}

Spring Data and Native Query with pagination

I could successfully integrate Pagination in

spring-data-jpa-2.1.6

as follows.

@Query(
 value = “SELECT * FROM Users”, 
 countQuery = “SELECT count(*) FROM Users”, 
 nativeQuery = true)
Page<User> findAllUsersWithPagination(Pageable pageable);

Determine distance from the top of a div to top of window with javascript

You can use .offset() to get the offset compared to the document element and then use the scrollTop property of the window element to find how far down the page the user has scrolled:

var scrollTop     = $(window).scrollTop(),
    elementOffset = $('#my-element').offset().top,
    distance      = (elementOffset - scrollTop);

The distance variable now holds the distance from the top of the #my-element element and the top-fold.

Here is a demo: http://jsfiddle.net/Rxs2m/

Note that negative values mean that the element is above the top-fold.

PySpark: multiple conditions in when clause

It should be:

$when(((tdata.Age == "" ) & (tdata.Survived == "0")), mean_age_0)

Select2 doesn't work when embedded in a bootstrap modal

Answer that worked for me found here: https://github.com/select2/select2-bootstrap-theme/issues/41

$('select').select2({
    dropdownParent: $('#my_amazing_modal')
});

Also doesn't require removing the tabindex.

How do I append text to a file?

Follow up to accepted answer.

You need something other than CTRL-D to designate the end if using this in a script. Try this instead:

cat << EOF >> filename
This is text entered via the keyboard or via a script.
EOF

This will append text to the stated file (not including "EOF").

It utilizes a here document (or heredoc).

However if you need sudo to append to the stated file, you will run into trouble utilizing a heredoc due to I/O redirection if you're typing directly on the command line.

This variation will work when you are typing directly on the command line:

sudo sh -c 'cat << EOF >> filename
This is text entered via the keyboard.
EOF'

Or you can use tee instead to avoid the command line sudo issue seen when using the heredoc with cat:

tee -a filename << EOF
This is text entered via the keyboard or via a script.
EOF

failed to open stream: No such file or directory in

Failed to open stream error occurs because the given path is wrong such as:

$uploadedFile->saveAs(Yii::app()->request->baseUrl.'/images/'.$model->user_photo);

It will give an error if the images folder will not allow you to store images, be sure your folder is readable

Jquery each - Stop loop and return object

"We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration."

from http://api.jquery.com/jquery.each/

Yea, this is old BUT, JUST to answer the question, this can be a bit simpler:

_x000D_
_x000D_
function findXX(word) {_x000D_
  $.each(someArray, function(index, value) {_x000D_
    $('body').append('-> ' + index + ":" + value + '<br />');_x000D_
    return !(value == word);_x000D_
  });_x000D_
}_x000D_
$(function() {_x000D_
  someArray = new Array();_x000D_
  someArray[0] = 't5';_x000D_
  someArray[1] = 'z12';_x000D_
  someArray[2] = 'b88';_x000D_
  someArray[3] = 's55';_x000D_
  someArray[4] = 'e51';_x000D_
  someArray[5] = 'o322';_x000D_
  someArray[6] = 'i22';_x000D_
  someArray[7] = 'k954';_x000D_
  findXX('o322');_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

A bit more with comments:

_x000D_
_x000D_
function findXX(myA, word) {_x000D_
  let br = '<br />';//create once_x000D_
  let myHolder = $("<div />");//get a holder to not hit DOM a lot_x000D_
  let found = false;//default return_x000D_
  $.each(myA, function(index, value) {_x000D_
    found = (value == word);_x000D_
    myHolder.append('-> ' + index + ":" + value + br);_x000D_
    return !found;_x000D_
  });_x000D_
  $('body').append(myHolder.html());// hit DOM once_x000D_
  return found;_x000D_
}_x000D_
$(function() {_x000D_
  // no horrid global array, easier array setup;_x000D_
  let someArray = ['t5', 'z12', 'b88', 's55', 'e51', 'o322', 'i22', 'k954'];_x000D_
  // pass the array and the value we want to find, return back a value_x000D_
  let test = findXX(someArray, 'o322');_x000D_
  $('body').append("<div>Found:" + test + "</div>");_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

NOTE: array .includes() may better suit here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Or just .find() to get that https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

Bootstrap row class contains margin-left and margin-right which creates problems

Old topic, but I think I found another descent solution. Adding class="row" to a div will result in this CSS configuration:

.row {
    display: -webkit-box;
    display: flex;
    flex-wrap: wrap;
    margin-right: -15px;
    margin-left: -15px;
}

We want to keep the first 3 rules and we can do this with class="d-flex flex-wrap" (see https://getbootstrap.com/docs/4.1/utilities/flex/):

.flex-wrap {
    flex-wrap: wrap !important;
}
.d-flex {
    display: -webkit-box !important;
    display: flex !important;
}

It adds !important rules though but it shouldn't be a problem in most cases...

Deleting row from datatable in C#

There several different ways to do it. But You can use the following approach:

List<DataRow> RowsToDelete = new List<DataRow>();

for (int i = 0; i < drr.Length; i++) 
{     
   if(condition to delete the row) 
   {  
       RowsToDelete.Add(drr[i]);     
   } 
}

foreach(var dr in RowsToDelete) 
{     
   drr.Rows.Remove(dr); 
} 

Visual Studio window which shows list of methods

Do you mean the class view window (View->Class View, or Ctrl+W,C)?

You also have the intellisence popup-window

Weird behavior of the != XPath operator

I've always used this syntax, which yields more predictable results than using !=.

<xsl:when test="not($AccountNumber = '12345') and not($Balance = '0')" />

postgresql - sql - count of `true` values

Cast the Boolean to an integer and sum.

SELECT count(*),sum(myCol::int);

You get 6,3.

AttributeError: Module Pip has no attribute 'main'

It appears that pip did a refactor and moved main to internal. There is a comprehensive discussion about it here: https://github.com/pypa/pip/issues/5240

A workaround for me was to change

import pip
pip.main(...)

to

from pip._internal import main
main(...)

I recommend reading through the discussion, I'm not sure this is the best approach, but it worked for my purposes.

Add a default value to a column through a migration

Here's how you should do it:

change_column :users, :admin, :boolean, :default => false

But some databases, like PostgreSQL, will not update the field for rows previously created, so make sure you update the field manaully on the migration too.

I can't find my git.exe file in my Github folder

The path for the latest version of Git is changed, In my laptop, I found it in

C:\Users\Anum Sheraz\AppData\Local\Programs\Git\bin\git.exe

This resolved my issue of path. Hope that helps to someone :)

How to wrap text of HTML button with fixed width?

You can force it (browser permitting, I imagine) by inserting line breaks in the HTML source, like this:

<INPUT value="Line 1
Line 2">

Of course working out where to place the line breaks is not necessarily trivial...

If you can use an HTML <BUTTON> instead of an <INPUT>, such that the button label is the element's content rather than its value attribute, placing that content inside a <SPAN> with a width attribute that is a few pixels narrower than that of the button seems to do the trick (even in IE6 :-).

Why doesn't Python have a sign function?

You dont need one, you can just use:

if not number == 0:
    sig = number/abs(number)
else:
    sig = 0

Or create a function as described by others:

sign = lambda x: bool(x > 0) - bool(x < 0)

def sign(x):
    return bool(x > 0) - bool(x < 0)

GroupBy pandas DataFrame and select most common value

Formally, the correct answer is the @eumiro Solution. The problem of @HYRY solution is that when you have a sequence of numbers like [1,2,3,4] the solution is wrong, i. e., you don't have the mode. Example:

>>> import pandas as pd
>>> df = pd.DataFrame(
        {
            'client': ['A', 'B', 'A', 'B', 'B', 'C', 'A', 'D', 'D', 'E', 'E', 'E', 'E', 'E', 'A'], 
            'total': [1, 4, 3, 2, 4, 1, 2, 3, 5, 1, 2, 2, 2, 3, 4], 
            'bla': [10, 40, 30, 20, 40, 10, 20, 30, 50, 10, 20, 20, 20, 30, 40]
        }
    )

If you compute like @HYRY you obtain:

>>> print(df.groupby(['client']).agg(lambda x: x.value_counts().index[0]))
        total  bla
client            
A           4   30
B           4   40
C           1   10
D           3   30
E           2   20

Which is clearly wrong (see the A value that should be 1 and not 4) because it can't handle with unique values.

Thus, the other solution is correct:

>>> import scipy.stats
>>> print(df.groupby(['client']).agg(lambda x: scipy.stats.mode(x)[0][0]))
        total  bla
client            
A           1   10
B           4   40
C           1   10
D           3   30
E           2   20

Change tab bar item selected color in a storyboard

Swift 3 | Xcode 10

If you want to make all tab bar items the same color (selected & unselected)...


Step 1

Make sure your image assets are setup to Render As = Template Image. This allows them to inherit color.

Xcode Assets


Step 2

Use the storyboard editor to change your tab bar settings as follows:

  • Set Tab Bar: Image Tint to the color you want the selected icon to inherit.
  • Set Tab Bar: Bar Tint to the color you want the tab bar to be.
  • Set View: Tint to the color you want to see in the storyboard editor, this doesn't affect the icon color when your app is run.

Xcode Storyboard Editor


Step 3

Steps 1 & 2 will change the color for the selected icon. If you still want to change the color of the unselected items, you need to do it in code. I haven't found a way to do it via the storyboard editor.

Create a custom tab bar controller class...

//  TabBarController.swift

class TabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // make unselected icons white
        self.tabBar.unselectedItemTintColor = UIColor.white
    }
}

... and assign the custom class to your tab bar scene controller.

Xcode Storyboard Editor


If you figure out how to change the unselected icon color via the storyboard editor please let me know. Thanks!

Set the layout weight of a TextView programmatically

After strugling for 4 hours. Finally, This code worked for me.

3 Columns are there in a row.

  TextView serialno = new TextView(UsersActivity.this);
  TextView userId = new TextView(UsersActivity.this);
  TextView name = new TextView(UsersActivity.this);

  serialno.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
  userId.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
  name.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));

Can you nest html forms?

As Craig said, no.

But, regarding your comment as to why:

It might be easier to use 1 <form> with the inputs and the "Update" button, and use copy hidden inputs with the "Submit Order" button in a another <form>.

Function of Project > Clean in Eclipse

I also faced the same issue with Eclipse when I ran the clean build with Maven, but there is a simple solution for this issue. We just need to run Maven update and then build or direct run the application. I hope it will solve the problem.

Pass C# ASP.NET array to Javascript array

Here is another alternative solution. You can use ClientScriptManager Page.ClientScript.RegisterArrayDeclaration. Here is an example for chart data.

var page = HttpContext.Current.CurrentHandler as Page;

_data = "[Date.UTC(2018, 9, 29, 0, 3), parseFloat(21.84)]
         ,[Date.UTC(2018, 9, 29, 0, 13), parseFloat(21.84)]
         ,[Date.UTC(2018, 9, 29, 0, 23), parseFloat(21.83)]
         ,[Date.UTC(2018, 9, 29, 0, 33), parseFloat(21.83)]";
page.ClientScript.RegisterArrayDeclaration("chartdata0", _data);

This code creates an array on the client side

var chartdata0 = new Array([Date.UTC(2018, 9, 29, 0, 3), parseFloat(21.84)]
             ,[Date.UTC(2018, 9, 29, 0, 13), parseFloat(21.84)]
             ,[Date.UTC(2018, 9, 29, 0, 23), parseFloat(21.83)]
             ,[Date.UTC(2018, 9, 29, 0, 33), parseFloat(21.83)]);

See the following article

https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.clientscriptmanager.registerarraydeclaration?view=netframework-4.8

This solution has an issue with bigger arrays on chrome 64 browser including "Version 78.0.3904.70 (Official Build) (64-bit)". You may get "Uncaught RangeError: Maximum call stack size exceeded". However it is working with IE11, Microsoft Edge, and FireFox.

Getting reference to child component in parent component

You may actually go with ViewChild API...

parent.ts

<button (click)="clicked()">click</button>

export class App {
  @ViewChild(Child) vc:Child;
  constructor() {
    this.name = 'Angular2'
  }

  func(e) {
    console.log(e)

  }
  clicked(){
   this.vc.getName();
  }
}

child.ts

export class Child implements OnInit{

  onInitialized = new EventEmitter<Child>();
  ...  
  ...
  getName()
  {
     console.log('called by vc')
     console.log(this.name);
  }
}

javascript convert int to float

toFixed() method formats a number using fixed-point notation. Read MDN Web Docs for full reference.

var fval = 4;

console.log(fval.toFixed(2)); // prints 4.00

Sorting arrays in javascript by object key value

here's an example with the accepted answer:

 a = [{name:"alex"},{name:"clex"},{name:"blex"}];

For Ascending :

a.sort((a,b)=> (a.name > b.name ? 1 : -1))

output : [{name: "alex"}, {name: "blex"},{name: "clex"} ]

For Decending :

a.sort((a,b)=> (a.name < b.name ? 1 : -1))

output : [{name: "clex"}, {name: "blex"}, {name: "alex"}]

Difference between PACKETS and FRAMES

Consider TCP over ATM. ATM uses 48 byte frames, but clearly TCP packets can be bigger than that. A frame is the chunk of data sent as a unit over the data link (Ethernet, ATM). A packet is the chunk of data sent as a unit over the layer above it (IP). If the data link is made specifically for IP, as Ethernet and WiFi are, these will be the same size and packets will correspond to frames.

Comparing two maps

As long as you override equals() on each key and value contained in the map, then m1.equals(m2) should be reliable to check for maps equality.

The same result can be obtained also by comparing toString() of each map as you suggested, but using equals() is a more intuitive approach.

May not be your specific situation, but if you store arrays in the map, may be a little tricky, because they must be compared value by value, or using Arrays.equals(). More details about this see here.

Chart won't update in Excel (2007)

I have run into this same issue - not sure why, and when it happens the only way I have ever gotten the chart to force update is to change something in the chart definition itself, which can easily be done via VBA as in:

Dim C As ChartObject: Set C = Me.ChartObjects("chart name")
C.Chart.ChartTitle.Text = C.Chart.ChartTitle.Text + "1"

There may be a better answer that gets to the bottom of the problem - but I thought this might help. Working on the sheet I would do a quick Ctrl-X, Ctrl-V on a piece of the chart (or the whole thing) to force the chart to update.

Converting Java objects to JSON with Jackson

To convert your object in JSON with Jackson:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);

jQuery Selector: Id Ends With?

An example: to select all <a>s with ID ending in _edit:

jQuery("a[id$=_edit]")

or

jQuery("a[id$='_edit']")

Argument list too long error for rm, cp, mv commands

I'm surprised there are no ulimit answers here. Every time I have this problem I end up here or here. I understand this solution has limitations but ulimit -s 65536 seems to often do the trick for me.

Add custom message to thrown exception while maintaining stack trace in Java

Following code is a simple example that worked for me.Let me call the function main as parent function and divide as child function.
Basically i am throwing a new exception with my custom message (for the parent's call) if an exception occurs in child function by catching the Exception in the child first.

class Main {
    public static void main(String args[]) {
        try{
            long ans=divide(0);
            System.out.println("answer="+ans);
        }
        catch(Exception e){
            System.out.println("got exception:"+e.getMessage());

        }

    }
    public static long divide(int num) throws Exception{
        long x=-1;
        try {
            x=5/num;
        }
        catch (Exception e){
            throw new Exception("Error occured in divide for number:"+num+"Error:"+e.getMessage());
        }
        return x;
    }
}  

the last line return x will not run if error occurs somewhere in between.

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

In our case, we had some extra lines in the .properties file which was not needed with the new image.

spring.jpa.properties.hibernate.cache.use_second_level_cache=true

Obviously with didn't had that Entity what it tried to load.

Create new user in MySQL and give it full access to one database

The below command will work if you want create a new user give him all the access to a specific database(not all databases in your Mysql) on your localhost.

GRANT ALL PRIVILEGES ON test_database.* TO 'user'@'localhost' IDENTIFIED BY 'password';

This will grant all privileges to one database test_database (in your case dbTest) to that user on localhost.

Check what permissions that above command issued to that user by running the below command.

SHOW GRANTS FOR 'user'@'localhost'

Just in case, if you want to limit the user access to only one single table

GRANT ALL ON mydb.table_name TO 'someuser'@'host';

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

MySQL direct INSERT INTO with WHERE clause

INSERT syntax cannot have WHERE but you can use UPDATE.

The syntax is as follows:

UPDATE table_name

SET column1 = value1, column2 = value2, ...

WHERE condition;

replace special characters in a string python

You need to call replace on z and not on str, since you want to replace characters located in the string variable z

removeSpecialChars = z.replace("!@#$%^&*()[]{};:,./<>?\|`~-=_+", " ")

But this will not work, as replace looks for a substring, you will most likely need to use regular expression module re with the sub function:

import re
removeSpecialChars = re.sub("[!@#$%^&*()[]{};:,./<>?\|`~-=_+]", " ", z)

Don't forget the [], which indicates that this is a set of characters to be replaced.

Unzip a file with php

you can use prepacked function

function unzip_file($file, $destination){
    // create object
    $zip = new ZipArchive() ;
    // open archive
    if ($zip->open($file) !== TRUE) {
        return false;
    }
    // extract contents to destination directory
    $zip->extractTo($destination);
    // close archive
    $zip->close();
        return true;
}

How to use it.

if(unzip_file($file["name"],'uploads/')){
echo 'zip archive extracted successfully';
}else{
  echo 'zip archive extraction failed';
}

Return None if Dictionary key is not available

You can use dict.get()

value = d.get(key)

which will return None if key is not in d. You can also provide a different default value that will be returned instead of None:

value = d.get(key, "empty")

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

When I faced this issue, I discovered that my problem was that the files in the 'Source Account' were copied there by a 'third party' and the Owner was not the Source Account.

I had to recopy the objects to themselves in the same bucket with the --metadata-directive REPLACE

Detailed explanation in Amazon Documentation

How to change Hash values?

You can collect the values, and convert it from Array to Hash again.

Like this:

config = Hash[ config.collect {|k,v| [k, v.upcase] } ]

asp.net: How can I remove an item from a dropdownlist?

I would add an identifying Id or class to the dropbox and remove using Javascript.

The article here should help.

D

HintPath vs ReferencePath in Visual Studio

According to this MSDN blog: https://blogs.msdn.microsoft.com/manishagarwal/2005/09/28/resolving-file-references-in-team-build-part-2/

There is a search order for assemblies when building. The search order is as follows:

  • Files from the current project – indicated by ${CandidateAssemblyFiles}.
  • $(ReferencePath) property that comes from .user/targets file.
  • %(HintPath) metadata indicated by reference item.
  • Target framework directory.
  • Directories found in registry that uses AssemblyFoldersEx Registration.
  • Registered assembly folders, indicated by ${AssemblyFolders}.
  • $(OutputPath) or $(OutDir)
  • GAC

So, if the desired assembly is found by HintPath, but an alternate assembly can be found using ReferencePath, it will prefer the ReferencePath'd assembly to the HintPath'd one.

How can I search sub-folders using glob.glob module?

There's a lot of confusion on this topic. Let me see if I can clarify it (Python 3.7):

  1. glob.glob('*.txt') :matches all files ending in '.txt' in current directory
  2. glob.glob('*/*.txt') :same as 1
  3. glob.glob('**/*.txt') :matches all files ending in '.txt' in the immediate subdirectories only, but not in the current directory
  4. glob.glob('*.txt',recursive=True) :same as 1
  5. glob.glob('*/*.txt',recursive=True) :same as 3
  6. glob.glob('**/*.txt',recursive=True):matches all files ending in '.txt' in the current directory and in all subdirectories

So it's best to always specify recursive=True.

How can I clear the NuGet package cache using the command line?

This adds to rm8x's answer.

Download and install the NuGet command line tool.

List all of our locals:

$ nuget locals all -list
http-cache: C:\Users\MyUser\AppData\Local\NuGet\v3-cache
packages-cache: C:\Users\MyUser\AppData\Local\NuGet\Cache
global-packages: C:\Users\MyUser\.nuget\packages\

We can now delete these manually or as rm8x suggests, use nuget locals all -clear.

Setting background color for a JFrame

I had trouble with changing the JFrame background as well and the above responses did not solve it entirely. I am using Eclipse. Adding a layout fixed the issue.

public class SampleProgram extends JFrame {
    public SampleProgram() {
        setSize(400,400);
        setTitle("Sample");
        getContentPane().setLayout(new FlowLayout());//specify a layout manager
        getContentPane().setBackground(Color.red);
        setVisible(true);
}

"Keep Me Logged In" - the best approach

Security Notice: Basing the cookie off an MD5 hash of deterministic data is a bad idea; it's better to use a random token derived from a CSPRNG. See ircmaxell's answer to this question for a more secure approach.

Usually I do something like this:

  1. User logs in with 'keep me logged in'
  2. Create session
  3. Create a cookie called SOMETHING containing: md5(salt+username+ip+salt) and a cookie called somethingElse containing id
  4. Store cookie in database
  5. User does stuff and leaves ----
  6. User returns, check for somethingElse cookie, if it exists, get the old hash from the database for that user, check of the contents of cookie SOMETHING match with the hash from the database, which should also match with a newly calculated hash (for the ip) thus: cookieHash==databaseHash==md5(salt+username+ip+salt), if they do, goto 2, if they don't goto 1

Off course you can use different cookie names etc. also you can change the content of the cookie a bit, just make sure it isn't to easily created. You can for example also create a user_salt when the user is created and also put that in the cookie.

Also you could use sha1 instead of md5 (or pretty much any algorithm)

Saving numpy array to txt file row wise

just

' '.join(a)

and write this output to a file.

How to place the ~/.composer/vendor/bin directory in your PATH?

For Ubuntu 16.04

echo 'export PATH="$PATH:$HOME/.config/composer/vendor/bin"' >> ~/.bashrc

source ~/.bashrc

Preloading @font-face fonts?

As I found the best way is doing is preloading a stylesheet that contains the font face, and then let browser to load it automatically. I used the font-face in other locations (in the html page), but then I could observe the font changing effect briefly.

<link href="fonts.css?family=Open+Sans" rel="preload stylesheet" as="style">

then in the font.css file, specify as following.

@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 400;
  src: local('Open Sans Regular'), local('OpenSans-Regular'),
       url('open-sans-v16-latin-regular.woff2') format('woff2'); /*  Super Modern Browsers */
}

You can't assign a name to fonts when it's preloaded through link tag (correct me if I was wrong I couldn't find a way yet), and thus you have to use font-face to assign the name to the font. Even though it's possible to load a font through link tag, it's not recommended as you can't assign a name to the font with it. Without a name as with font-face, you won't be able to use it anywhere in the web page. According to gtmetrix, style sheet loads at the beginning, then rest of the scripts/style by order, then the font before dom is loaded, and therefore you don't see font changing effect.

Keras model.summary() result - Understanding the # of Parameters

The "none" in the shape means it does not have a pre-defined number. For example, it can be the batch size you use during training, and you want to make it flexible by not assigning any value to it so that you can change your batch size. The model will infer the shape from the context of the layers.

To get nodes connected to each layer, you can do the following:

for layer in model.layers:
    print(layer.name, layer.inbound_nodes, layer.outbound_nodes)

Change Title of Javascript Alert

As others have said, you can't do that either using alert()or confirm().

You can, however, create an external HTML document containing your error message and an OK button, set its <title> element to whatever you want, then display it in a modal dialog box using showModalDialog().

Find an object in SQL Server (cross-database)

SELECT NAME AS ObjectName
    ,schema_name(o.schema_id) AS SchemaName, OBJECT_NAME(o.parent_object_id) as TableName
    ,type
    ,o.type_desc
FROM sys.objects o
WHERE o.is_ms_shipped = 0
    AND o.NAME LIKE '%UniqueID%'
ORDER BY o.NAME

OpenCV with Network Cameras

OpenCV can be compiled with FFMPEG support. From ./configure --help:

--with-ffmpeg     use ffmpeg libraries (see LICENSE) [automatic]

You can then use cvCreateFileCapture_FFMPEG to create a CvCapture with e.g. the URL of the camera's MJPG stream.

I use this to grab frames from an AXIS camera:

CvCapture *capture = 
    cvCreateFileCapture_FFMPEG("http://axis-cam/mjpg/video.mjpg?resolution=640x480&req_fps=10&.mjpg");

Percentage Height HTML 5/CSS

Hi! In order to use percentage(%), you must define the % of it parent element. If you use body{height: 100%} it will not work because it parent have no percentage in height. In that case in order to work that body height you must add this in html{height:100%}

In other case to get rid of that defining parent percentage you can use

body{height:100vh}

vh stands for viewport height

I think it help

Serialize and Deserialize Json and Json Array in Unity

Don't trim the [] and you should be fine. [] identify a JSON array which is exactly what you require to be able to iterate its elements.

Real-world examples of recursion

Phone and cable companies maintain a model of their wiring topology, which in effect is a large network or graph. Recursion is one way to traverse this model when you want to find all parent or all child elements.

Since recursion is expensive from a processing and memory perspective, this step is commonly only performed when the topology is changed and the result is stored in a modified pre-ordered list format.

"Object doesn't support property or method 'find'" in IE

You are using the JavaScript array.find() method. Note that this is standard JS, and has nothing to do with jQuery. In fact, your entire code in the question makes no use of jQuery at all.

You can find the documentation for array.find() here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find

If you scroll to the bottom of this page, you will note that it has browser support info, and you will see that it states that IE does not support this method.

Ironically, your best way around this would be to use jQuery, which does have similar functionality that is supported in all browsers.

rand() returns the same number each time the program is run

For what its worth you are also only generating numbers between 0 and 99 (inclusive). If you wanted to generate values between 0 and 100 you would need.

rand() % 101

in addition to calling srand() as mentioned by others.

C++: Print out enum value as text

For this problem, I do a help function like this:

const char* name(Id id) {
    struct Entry {
        Id id;
        const char* name;
    };
    static const Entry entries[] = {
        { ErrorA, "ErrorA" },
        { ErrorB, "ErrorB" },
        { 0, 0 }
    }
    for (int it = 0; it < gui::SiCount; ++it) {
        if (entries[it].id == id) {
            return entries[it].name;
        }
    }
   return 0;
}

Linear search is usually more efficient than std::map for small collections like this.

Upload folder with subfolders using S3 and the AWS console

I was having problem with finding the enhanced uploader tool for uploading folder and subfolders inside it in S3. But rather than finding a tool I could upload the folders along with the subfolders inside it by simply dragging and dropping it in the S3 bucket.

Note: This drag and drop feature doesn't work in Safari. I've tested it in Chrome and it works just fine.

Drag and drop

After you drag and drop the files and folders, this screen opens up finally to upload the content.

enter image description here

Android Fragment no view found for ID?

I use View Binding in my project and was inattentive to add setContentView() after inflating ActivityHelloWorldBinding class:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityHelloWorldBinding.inflate(layoutInflater)

    // Add this line.
    setContentView(binding.root)
}

source of historical stock data

Let me add my 2¢, it's my job to get good and clean data for a hedge-fund, I've seen quite a lot of data feeds and historical data providers. This is mainly about US stock data.

To start with, if you have some money don't bother with downloading data from Yahoo, get the end of day data straight from CSI data, this is where Yahoo gets their EOD data as well AFAIK. They have an API where you can extract the data to whatever format you want. I think the yearly subscription for data is a few $100 bucks.

The main problem with downloading data from a free service is that you only get stocks that still exist, this is called Survivorship Bias and can give you wrong results if you look at many stocks, because you'll only include the ones that made it so far and not the ones that were de-listed.

For playing around with some intraday data I'd look into IQFeed, they provide several APIs to extract historical data, although they are mainly an outfit for real-time feeds. But here there are quite a few options, some brokers even provide historical data downloads via their APIs, so just pick your poison.

BUT usually all of this data is not very clean, once you really start back testing you'll see that certain stocks are missing or appear as two different symbols, or stock splits are not properly accounted for, etc. And then you realize that historical dividend data is need as well and so you start running in circles, patching data together from 100 different data sources and so on. So to start with a "discount" data feed will do, but as soon as you run more comprehensive backtests you might run into problems depending on what you do. If you just look at, let's say, the S&P 500 stocks this will not be so much a problem though and a "cheap" intraday feed will do.

What you will not find is free intraday data. I mean you might find some examples, I'm sure there's somewhere 5 years of MSFT tick data floating around but that will not get you very far.

Then, if you need the real stuff (level II order book, all ticks as they have happened at all exchanges) one "affordable", yet excellent option is Nanex. They'll actually ship you a drive with terabytes of data. If I remember right its about $3k-4K per year of data. But trust me, once you understand how hard it is to get good intraday data, you won't think this is very much money at all.

Not to discourage you but to get good data is hard, so hard in fact that many hedge-funds and banks spend hundreds of thousands of dollars a month to get data they can trust. Again, you can start somewhere and then go from there but it's good to see it a bit in context.


Edit: The answer above is from my own experience. This write-up from Caltech about available data feeds will give more insights, and especially recommends QuantQuote.

List of Java processes

When I want to know if a certain Java class is getting executed, I use the following command line:

ps ww -f -C java | grep "fully.qualified.name.of.class"

From the OS side view, the process's command name is "java". The "ww" option widens the colum's maximum characters, so it's possible to grep the FQN of the related class.

'pip install' fails for every package ("Could not find a version that satisfies the requirement")

Upgrade pip as follows:

curl https://bootstrap.pypa.io/get-pip.py | python

Note: You may need to use sudo python above if not in a virtual environment.

What's happening:

Python.org sites are stopping support for TLS versions 1.0 and 1.1. This means that Mac OS X version 10.12 (Sierra) or older will not be able to use pip unless they upgrade pip as above.

(Note that upgrading pip via pip install --upgrade pip will also not upgrade it correctly. It is a chicken-and-egg issue)

This thread explains it (thanks to this Twitter post):

Mac users who use pip and PyPI:

If you are running macOS/OS X version 10.12 or older, then you ought to upgrade to the latest pip (9.0.3) to connect to the Python Package Index securely:

curl https://bootstrap.pypa.io/get-pip.py | python

and we recommend you do that by April 8th.

Pip 9.0.3 supports TLSv1.2 when running under system Python on macOS < 10.13. Official release notes: https://pip.pypa.io/en/stable/news/

Also, the Python status page:

Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC

Update - The rolling brownouts have been upgraded to a blackout, TLSv1.0 and TLSv1.1 will be rejected with a HTTP 403 at all times. Apr 8, 15:49 UTC

Lastly, to avoid other install errors, make sure you also upgrade setuptools after doing the above:

pip install --upgrade setuptools

How to actually search all files in Visual Studio

One can access the "Find in Files" window via the drop-down menu selection and search all files in the Entire Solution: Edit > Find and Replace > Find in Files

enter image description here

Other, alternative is to open the "Find in Files" window via the "Standard Toolbars" button as highlighted in the below screen-short:

enter image description here

How do I install PHP cURL on Linux Debian?

I wrote an article on topis how to [manually install curl on debian linu][1]x.

[1]: http://www.jasom.net/how-to-install-curl-command-manually-on-debian-linux. This is its shortcut:

  1. cd /usr/local/src
  2. wget http://curl.haxx.se/download/curl-7.36.0.tar.gz
  3. tar -xvzf curl-7.36.0.tar.gz
  4. rm *.gz
  5. cd curl-7.6.0
  6. ./configure
  7. make
  8. make install

And restart Apache. If you will have an error during point 6, try to run apt-get install build-essential.

Count number of rows within each group

Considering @Ben answer, R would throw an error if df1 does not contain x column. But it can be solved elegantly with paste:

aggregate(paste(Year, Month) ~ Year + Month, data = df1, FUN = NROW)

Similarly, it can be generalized if more than two variables are used in grouping:

aggregate(paste(Year, Month, Day) ~ Year + Month + Day, data = df1, FUN = NROW)

Call external javascript functions from java code

Let us say your jsfunctions.js file has a function "display" and this file is stored in C:/Scripts/Jsfunctions.js

jsfunctions.js

var display = function(name) {
print("Hello, I am a Javascript display function",name);
return "display function return"
}

Now, in your java code, I would recommend you to use Java8 Nashorn. In your java class,

import java.io.FileNotFoundException;
import java.io.FileReader;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

class Test {
public void runDisplay() {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
try {
  engine.eval(new FileReader("C:/Scripts/Jsfunctions.js"));
  Invocable invocable = (Invocable) engine;
  Object result;
  result = invocable.invokeFunction("display", helloWorld);
  System.out.println(result);
  System.out.println(result.getClass());
  } catch (FileNotFoundException | NoSuchMethodException | ScriptException e) {
    e.printStackTrace();
    }
  }
}

Note: Get the absolute path of your javascript file and replace in FileReader() and run the java code. It should work.

How can I list ALL grants a user received?

Sorry guys, but selecting from all_tab_privs_recd where grantee = 'your user' will not give any output except public grants and current user grants if you run the select from a different (let us say, SYS) user. As documentation says,

ALL_TAB_PRIVS_RECD describes the following types of grants:

Object grants for which the current user is the grantee
Object grants for which an enabled role or PUBLIC is the grantee

So, if you're a DBA and want to list all object grants for a particular (not SYS itself) user, you can't use that system view.

In this case, you must perform a more complex query. Here is one taken (traced) from TOAD to select all object grants for a particular user:

select tpm.name privilege,
       decode(mod(oa.option$,2), 1, 'YES', 'NO') grantable,
       ue.name grantee,
       ur.name grantor,
       u.name owner,
       decode(o.TYPE#, 0, 'NEXT OBJECT', 1, 'INDEX', 2, 'TABLE', 3, 'CLUSTER',
                       4, 'VIEW', 5, 'SYNONYM', 6, 'SEQUENCE',
                       7, 'PROCEDURE', 8, 'FUNCTION', 9, 'PACKAGE',
                       11, 'PACKAGE BODY', 12, 'TRIGGER',
                       13, 'TYPE', 14, 'TYPE BODY',
                       19, 'TABLE PARTITION', 20, 'INDEX PARTITION', 21, 'LOB',
                       22, 'LIBRARY', 23, 'DIRECTORY', 24, 'QUEUE',
                       28, 'JAVA SOURCE', 29, 'JAVA CLASS', 30, 'JAVA RESOURCE',
                       32, 'INDEXTYPE', 33, 'OPERATOR',
                       34, 'TABLE SUBPARTITION', 35, 'INDEX SUBPARTITION',
                       40, 'LOB PARTITION', 41, 'LOB SUBPARTITION',
                       42, 'MATERIALIZED VIEW',
                       43, 'DIMENSION',
                       44, 'CONTEXT', 46, 'RULE SET', 47, 'RESOURCE PLAN',
                       66, 'JOB', 67, 'PROGRAM', 74, 'SCHEDULE',
                       48, 'CONSUMER GROUP',
                       51, 'SUBSCRIPTION', 52, 'LOCATION',
                       55, 'XML SCHEMA', 56, 'JAVA DATA',
                       57, 'EDITION', 59, 'RULE',
                       62, 'EVALUATION CONTEXT',
                       'UNDEFINED') object_type,
       o.name object_name,
       '' column_name
        from sys.objauth$ oa, sys.obj$ o, sys.user$ u, sys.user$ ur, sys.user$ ue,
             table_privilege_map tpm
        where oa.obj# = o.obj#
          and oa.grantor# = ur.user#
          and oa.grantee# = ue.user#
          and oa.col# is null
          and oa.privilege# = tpm.privilege
          and u.user# = o.owner#
          and o.TYPE# in (2, 4, 6, 9, 7, 8, 42, 23, 22, 13, 33, 32, 66, 67, 74, 57)
  and ue.name = 'your user'
  and bitand (o.flags, 128) = 0
union all -- column level grants
select tpm.name privilege,
       decode(mod(oa.option$,2), 1, 'YES', 'NO') grantable,
       ue.name grantee,
       ur.name grantor,
       u.name owner,
       decode(o.TYPE#, 2, 'TABLE', 4, 'VIEW', 42, 'MATERIALIZED VIEW') object_type,
       o.name object_name,
       c.name column_name
from sys.objauth$ oa, sys.obj$ o, sys.user$ u, sys.user$ ur, sys.user$ ue,
     sys.col$ c, table_privilege_map tpm
where oa.obj# = o.obj#
  and oa.grantor# = ur.user#
  and oa.grantee# = ue.user#
  and oa.obj# = c.obj#
  and oa.col# = c.col#
  and bitand(c.property, 32) = 0 /* not hidden column */
  and oa.col# is not null
  and oa.privilege# = tpm.privilege
  and u.user# = o.owner#
  and o.TYPE# in (2, 4, 42)
  and ue.name = 'your user'
  and bitand (o.flags, 128) = 0;

This will list all object grants (including column grants) for your (specified) user. If you don't want column level grants then delete all part of the select beginning with 'union' clause.

UPD: Studying the documentation I found another view that lists all grants in much simpler way:

select * from DBA_TAB_PRIVS where grantee = 'your user';

Bear in mind that there's no DBA_TAB_PRIVS_RECD view in Oracle.

How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#?

For Java:

driver.manage().window().maximize();

It will work in IE, Mozilla, Chrome

Install IPA with iTunes 12

Edit: See Jayprakash Dubey's answer for iTunes 12.7


From the menu shown in the following screenshot, choose Apps. You can drag and drop you IPA file in the next view.

enter image description here

After that, go to your device's page, you'll see the list of apps, install your app and press Apply from the bottom bar.

str.startswith with a list of strings to test for

You can also use any(), map() like so:

if any(map(l.startswith, x)):
    pass # Do something

Or alternatively, using a generator expression:

if any(l.startswith(s) for s in x)
    pass # Do something

UIScrollView scroll to bottom programmatically

Xamarin.iOS version of accepted answer

var bottomOffset = new CGPoint (0,
     scrollView.ContentSize.Height - scrollView.Frame.Size.Height
     + scrollView.ContentInset.Bottom);

scrollView.SetContentOffset (bottomOffset, false);

Mock functions in Go

I'm using a slightly different approach where public struct methods implement interfaces but their logic is limited to just wrapping private (unexported) functions which take those interfaces as parameters. This gives you the granularity you would need to mock virtually any dependency and yet have a clean API to use from outside your test suite.

To understand this it is imperative to understand that you have access to the unexported methods in your test case (i.e. from within your _test.go files) so you test those instead of testing the exported ones which have no logic inside beside wrapping.

To summarize: test the unexported functions instead of testing the exported ones!

Let's make an example. Say that we have a Slack API struct which has two methods:

  • the SendMessage method which sends an HTTP request to a Slack webhook
  • the SendDataSynchronously method which given a slice of strings iterates over them and calls SendMessage for every iteration

So in order to test SendDataSynchronously without making an HTTP request each time we would have to mock SendMessage, right?

package main

import (
    "fmt"
)

// URI interface
type URI interface {
    GetURL() string
}

// MessageSender interface
type MessageSender interface {
    SendMessage(message string) error
}

// This one is the "object" that our users will call to use this package functionalities
type API struct {
    baseURL  string
    endpoint string
}

// Here we make API implement implicitly the URI interface
func (api *API) GetURL() string {
    return api.baseURL + api.endpoint
}

// Here we make API implement implicitly the MessageSender interface
// Again we're just WRAPPING the sendMessage function here, nothing fancy 
func (api *API) SendMessage(message string) error {
    return sendMessage(api, message)
}

// We want to test this method but it calls SendMessage which makes a real HTTP request!
// Again we're just WRAPPING the sendDataSynchronously function here, nothing fancy
func (api *API) SendDataSynchronously(data []string) error {
    return sendDataSynchronously(api, data)
}

// this would make a real HTTP request
func sendMessage(uri URI, message string) error {
    fmt.Println("This function won't get called because we will mock it")
    return nil
}

// this is the function we want to test :)
func sendDataSynchronously(sender MessageSender, data []string) error {
    for _, text := range data {
        err := sender.SendMessage(text)

        if err != nil {
            return err
        }
    }

    return nil
}

// TEST CASE BELOW

// Here's our mock which just contains some variables that will be filled for running assertions on them later on
type mockedSender struct {
    err      error
    messages []string
}

// We make our mock implement the MessageSender interface so we can test sendDataSynchronously
func (sender *mockedSender) SendMessage(message string) error {
    // let's store all received messages for later assertions
    sender.messages = append(sender.messages, message)

    return sender.err // return error for later assertions
}

func TestSendsAllMessagesSynchronously() {
    mockedMessages := make([]string, 0)
    sender := mockedSender{nil, mockedMessages}

    messagesToSend := []string{"one", "two", "three"}
    err := sendDataSynchronously(&sender, messagesToSend)

    if err == nil {
        fmt.Println("All good here we expect the error to be nil:", err)
    }

    expectedMessages := fmt.Sprintf("%v", messagesToSend)
    actualMessages := fmt.Sprintf("%v", sender.messages)

    if expectedMessages == actualMessages {
        fmt.Println("Actual messages are as expected:", actualMessages)
    }
}

func main() {
    TestSendsAllMessagesSynchronously()
}

What I like about this approach is that by looking at the unexported methods you can clearly see what the dependencies are. At the same time the API that you export is a lot cleaner and with less parameters to pass along since the true dependency here is just the parent receiver which is implementing all those interfaces itself. Yet every function is potentially depending only on one part of it (one, maybe two interfaces) which makes refactors a lot easier. It's nice to see how your code is really coupled just by looking at the functions signatures, I think it makes a powerful tool against smelling code.

To make things easy I put everything into one file to allow you to run the code in the playground here but I suggest you also check out the full example on GitHub, here is the slack.go file and here the slack_test.go.

And here the whole thing.

How to join multiple collections with $lookup in mongodb

According to the documentation, $lookup can join only one external collection.

What you could do is to combine userInfo and userRole in one collection, as provided example is based on relational DB schema. Mongo is noSQL database - and this require different approach for document management.

Please find below 2-step query, which combines userInfo with userRole - creating new temporary collection used in last query to display combined data. In last query there is an option to use $out and create new collection with merged data for later use.

create collections

db.sivaUser.insert(
{    
    "_id" : ObjectId("5684f3c454b1fd6926c324fd"),
        "email" : "[email protected]",
        "userId" : "AD",
        "userName" : "admin"
})

//"userinfo"
db.sivaUserInfo.insert(
{
    "_id" : ObjectId("56d82612b63f1c31cf906003"),
    "userId" : "AD",
    "phone" : "0000000000"
})

//"userrole"
db.sivaUserRole.insert(
{
    "_id" : ObjectId("56d82612b63f1c31cf906003"),
    "userId" : "AD",
    "role" : "admin"
})

"join" them all :-)

db.sivaUserInfo.aggregate([
    {$lookup:
        {
           from: "sivaUserRole",
           localField: "userId",
           foreignField: "userId",
           as: "userRole"
        }
    },
    {
        $unwind:"$userRole"
    },
    {
        $project:{
            "_id":1,
            "userId" : 1,
            "phone" : 1,
            "role" :"$userRole.role"
        }
    },
    {
        $out:"sivaUserTmp"
    }
])


db.sivaUserTmp.aggregate([
    {$lookup:
        {
           from: "sivaUser",
           localField: "userId",
           foreignField: "userId",
           as: "user"
        }
    },
    {
        $unwind:"$user"
    },
    {
        $project:{
            "_id":1,
            "userId" : 1,
            "phone" : 1,
            "role" :1,
            "email" : "$user.email",
            "userName" : "$user.userName"
        }
    }
])

ios app maximum memory budget

You should watch session 147 from the WWDC 2010 Session videos. It is "Advanced Performance Optimization on iPhone OS, part 2".
There is a lot of good advice on memory optimizations.

Some of the tips are:

  • Use nested NSAutoReleasePools to make sure your memory usage does not spike.
  • Use CGImageSource when creating thumbnails from large images.
  • Respond to low memory warnings.

How to pass multiple parameter to @Directives (@Components) in Angular with TypeScript?

Similar to the above solutions I used @Input() in a directive and able to pass multiple arrays of values in the directive.

selector: '[selectorHere]',

@Input() options: any = {};

Input.html

<input selectorHere [options]="selectorArray" />

Array from TS file

selectorArray= {
  align: 'left',
  prefix: '$',
  thousands: ',',
  decimal: '.',
  precision: 2
};

How can I get the current time in C#?

try this:

 string.Format("{0:HH:mm:ss tt}", DateTime.Now);

for further details you can check it out : How do you get the current time of day?

How to label scatterplot points by name?

Another convoluted answer which should technically work and is ok for a small number of data points is to plot all your data points as 1 series in order to get your connecting line. Then plot each point as its own series. Then format data labels to display series name for each of the individual data points.

In short it works ok for a small data set or just key points from a data set.

Disable vertical sync for glxgears

I found a solution that works in the intel card and in the nvidia card using Bumblebee.

> export vblank_mode=0
glxgears
...
optirun glxgears
...
export vblank_mode=1

Click to call html

tl;dr What to do in modern (2018) times? Assume tel: is supported, use it and forget about anything else.


The tel: URI scheme RFC5431 (as well as sms: but also feed:, maps:, youtube: and others) is handled by protocol handlers (as mailto: and http: are).

They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto: protocol handler with same meaning and behaviour of tel: but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.

What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler() and related functions) simplifying also the check for their support through isProtocolHandlerRegistered() function.

There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).

In general what I suggest is:

  1. If you're running on a mobile device then you can safely assume tel: is supported (yes, it's not true for very old devices but IMO you can ignore them).
  2. If JS isn't active then do nothing.
  3. If you're running on desktop browsers then you can use one of the techniques in the linked post to determine if it's supported.
  4. If tel: isn't supported then change links to use callto: and repeat check desctibed in 3.
  5. If tel: and callto: aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href with javascript:void(0) and (if number isn't repeated in text span) putting, telephone number in title. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto: and tel:.

Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:

  1. If you're running on a mobile device then assume tel: is supported.
  2. If you're running on desktop then replace tel: with callto:. then drop tel: or leave it as is (assuming there are good chances Skype is installed).

How do I accomplish an if/else in mustache.js?

You can define a helper in the view. However, the conditional logic is somewhat limited. Moxy-Stencil (https://github.com/dcmox/moxyscript-stencil) seems to address this with "parameterized" helpers, eg:

{{isActive param}}

and in the view:

view.isActive = function (path: string){ return path === this.path ? "class='active'" : '' }

How do I properly force a Git push?

And if push --force doesn't work you can do push --delete. Look at 2nd line on this instance:

git reset --hard HEAD~3  # reset current branch to 3 commits ago
git push origin master --delete  # do a very very bad bad thing
git push origin master  # regular push

But beware...

Never ever go back on a public git history!

In other words:

  • Don't ever force push on a public repository.
  • Don't do this or anything that can break someone's pull.
  • Don't ever reset or rewrite history in a repo someone might have already pulled.

Of course there are exceptionally rare exceptions even to this rule, but in most cases it's not needed to do it and it will generate problems to everyone else.

Do a revert instead.

And always be careful with what you push to a public repo. Reverting:

git revert -n HEAD~3..HEAD  # prepare a new commit reverting last 3 commits
git commit -m "sorry - revert last 3 commits because I was not careful"
git push origin master  # regular push

In effect, both origin HEADs (from the revert and from the evil reset) will contain the same files.


edit to add updated info and more arguments around push --force

Consider pushing force with lease instead of push, but still prefer revert

Another problem push --force may bring is when someone push anything before you do, but after you've already fetched. If you push force your rebased version now you will replace work from others.

git push --force-with-lease introduced in the git 1.8.5 (thanks to @VonC comment on the question) tries to address this specific issue. Basically, it will bring an error and not push if the remote was modified since your latest fetch.

This is good if you're really sure a push --force is needed, but still want to prevent more problems. I'd go as far to say it should be the default push --force behaviour. But it's still far from being an excuse to force a push. People who fetched before your rebase will still have lots of troubles, which could be easily avoided if you had reverted instead.

And since we're talking about git --push instances...

Why would anyone want to force push?

@linquize brought a good push force example on the comments: sensitive data. You've wrongly leaked data that shouldn't be pushed. If you're fast enough, you can "fix"* it by forcing a push on top.

* The data will still be on the remote unless you also do a garbage collect, or clean it somehow. There is also the obvious potential for it to be spread by others who'd fetched it already, but you get the idea.

Scrollview vertical and horizontal in android

Mixing some of the suggestions above, and was able to get a good solution:

Custom ScrollView:

package com.scrollable.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ScrollView;

public class VScroll extends ScrollView {

    public VScroll(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public VScroll(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public VScroll(Context context) {
        super(context);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return false;
    }
}

Custom HorizontalScrollView:

package com.scrollable.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView;

public class HScroll extends HorizontalScrollView {

    public HScroll(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public HScroll(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public HScroll(Context context) {
        super(context);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return false;
    }
}

the ScrollableImageActivity:

package com.scrollable.view;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView;
import android.widget.ScrollView;

public class ScrollableImageActivity extends Activity {

    private float mx, my;
    private float curX, curY;

    private ScrollView vScroll;
    private HorizontalScrollView hScroll;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        vScroll = (ScrollView) findViewById(R.id.vScroll);
        hScroll = (HorizontalScrollView) findViewById(R.id.hScroll);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float curX, curY;

        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:
                mx = event.getX();
                my = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                curX = event.getX();
                curY = event.getY();
                vScroll.scrollBy((int) (mx - curX), (int) (my - curY));
                hScroll.scrollBy((int) (mx - curX), (int) (my - curY));
                mx = curX;
                my = curY;
                break;
            case MotionEvent.ACTION_UP:
                curX = event.getX();
                curY = event.getY();
                vScroll.scrollBy((int) (mx - curX), (int) (my - curY));
                hScroll.scrollBy((int) (mx - curX), (int) (my - curY));
                break;
        }

        return true;
    }

}

the layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <com.scrollable.view.VScroll android:layout_height="fill_parent"
        android:layout_width="fill_parent" android:id="@+id/vScroll">
        <com.scrollable.view.HScroll android:id="@+id/hScroll"
            android:layout_width="fill_parent" android:layout_height="fill_parent">
            <ImageView android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/bg"></ImageView>
        </com.scrollable.view.HScroll>
    </com.scrollable.view.VScroll>

</LinearLayout>

Cannot convert lambda expression to type 'string' because it is not a delegate type

My case it solved i was using

@Html.DropDownList(model => model.TypeId ...)  

using

@Html.DropDownListFor(model => model.TypeId ...) 

will solve it

JVM heap parameters

if you wrote: -Xms512m -Xmx512m when it start, java allocate in those moment 512m of ram for his process and cant increment.

-Xms64m -Xmx512m when it start, java allocate only 64m of ram for his process, but java can be increment his memory occupation while 512m.

I think that second thing is better because you give to java the automatic memory management.

Remove empty lines in a text file via grep

Try the following:

grep -v -e '^$'

Hive: how to show all partitions of a table?

CLI has some limit when ouput is displayed. I suggest to export output into local file:

$hive -e 'show partitions table;' > partitions

Running a CMD or BAT in silent mode

Include the phrase:

@echo off

Right at the top of your bat script.

PLS-00428: an INTO clause is expected in this SELECT statement

In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.

The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.

DECLARE
   PROD_ROW_ID   VARCHAR (10) := NULL;
   VIS_ROW_ID    NUMBER;
   DSC           VARCHAR (512);
BEGIN
   SELECT ROW_ID
     INTO VIS_ROW_ID
     FROM SIEBEL.S_PROD_INT
    WHERE PART_NUM = 'S0146404';

   BEGIN
      SELECT    RTRIM (VIS.SERIAL_NUM)
             || ','
             || RTRIM (PLANID.DESC_TEXT)
             || ','
             || CASE
                   WHEN PLANID.HIGH = 'TEST123'
                   THEN
                      CASE
                         WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
                         THEN
                            'Y'
                         ELSE
                            'N'
                      END
                   ELSE
                      'N'
                END
             || ','
             || 'GB'
             || ','
             || RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
        INTO DSC
        FROM SIEBEL.S_LST_OF_VAL PLANID
             INNER JOIN SIEBEL.S_PROD_INT PROD
                ON PROD.PART_NUM = PLANID.VAL
             INNER JOIN SIEBEL.S_ASSET NETFLIX
                ON PROD.PROD_ID = PROD.ROW_ID
             INNER JOIN SIEBEL.S_ASSET VIS
                ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
             INNER JOIN SIEBEL.S_PROD_INT VISPROD
                ON VIS.PROD_ID = VISPROD.ROW_ID
       WHERE     PLANID.TYPE = 'Test Plan'
             AND PLANID.ACTIVE_FLG = 'Y'
             AND VISPROD.PART_NUM = VIS_ROW_ID
             AND PROD.STATUS_CD = 'Active'
             AND VIS.SERIAL_NUM IS NOT NULL;
   END;
END;
/

References

http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/

jquery append external html file into my page

Use html instead of append:

$.get("banner.html", function(data){
    $(this).children("div:first").html(data);
});

How to store arbitrary data for some HTML tags

Arbitrary attributes are not valid, but are perfectly reliable in modern browsers. If you are setting the properties via javascript, than you don't have to worry about validation as well.

An alternative is to set attributes in javascript. jQuery has a nice utility method just for that purpose, or you can roll your own.

Displaying better error message than "No JSON object could be decoded"

You could use cjson, that claims to be up to 250 times faster than pure-python implementations, given that you have "some long complicated JSON file" and you will probably need to run it several times (decoders fail and report the first error they encounter only).

What's the difference between Perl's backticks, system, and exec?

Let me quote the manuals first:

perldoc exec():

The exec function executes a system command and never returns-- use system instead of exec if you want it to return

perldoc system():

Does exactly the same thing as exec LIST , except that a fork is done first, and the parent process waits for the child process to complete.

In contrast to exec and system, backticks don't give you the return value but the collected STDOUT.

perldoc `String`:

A string which is (possibly) interpolated and then executed as a system command with /bin/sh or its equivalent. Shell wildcards, pipes, and redirections will be honored. The collected standard output of the command is returned; standard error is unaffected.


Alternatives:

In more complex scenarios, where you want to fetch STDOUT, STDERR or the return code, you can use well known standard modules like IPC::Open2 and IPC::Open3.

Example:

use IPC::Open2;
my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'some', 'cmd', 'and', 'args');
waitpid( $pid, 0 );
my $child_exit_status = $? >> 8;

Finally, IPC::Run from the CPAN is also worth looking at…

Facebook development in localhost

Here is my config and it works fine for PHP API:

app domain

   http://localhost

Site URL

   http://localhost:8082/

Link to add to Google calendar

Here's an example link you can use to see the format:

https://www.google.com/calendar/render?action=TEMPLATE&text=Your+Event+Name&dates=20140127T224000Z/20140320T221500Z&details=For+details,+link+here:+http://www.example.com&location=Waldorf+Astoria,+301+Park+Ave+,+New+York,+NY+10022&sf=true&output=xml

Note the key query parameters:

text
dates
details
location

Here's another example (taken from http://wordpress.org/support/topic/direct-link-to-add-specific-google-calendar-event):

<a href="http://www.google.com/calendar/render?
action=TEMPLATE
&text=[event-title]
&dates=[start-custom format='Ymd\\THi00\\Z']/[end-custom format='Ymd\\THi00\\Z']
&details=[description]
&location=[location]
&trp=false
&sprop=
&sprop=name:"
target="_blank" rel="nofollow">Add to my calendar</a>

Here's a form which will help you construct such a link if you want (mentioned in earlier answers):

https://support.google.com/calendar/answer/3033039 Edit: This link no longer gives you a form you can use

How to set Toolbar text and back arrow color

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/actionBar"
app:titleTextAppearance="@style/ToolbarTitleText"
app:theme="@style/ToolBarStyle">

<TextView
    android:id="@+id/title"
    style="@style/ToolbarTitleText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="hh"/>

<!-- ToolBar -->
<style name="ToolBarStyle" parent="Widget.AppCompat.Toolbar">
    <item name="actionMenuTextColor">#ff63BBF7</item>
</style>

use app:theme="@style/ToolBarStyle"

Reference resources:http://blog.csdn.net/wyyl1/article/details/45972371

ng-repeat: access key and value for each object in array of objects

In fact, your data is not well design. You'd better use something like :

$scope.steps = [
    {stepName: "companyName", isComplete: true},
    {stepName: "businessType", isComplete: true},
    {stepName: "physicalAddress", isComplete: true}
];

Then it is easy to do what you want :

<div ng-repeat="step in steps">
 Step {{step.stepName}} status : {{step.isComplet}}
</div>

Example: http://jsfiddle.net/rX7ba/

How to edit the size of the submit button on a form?

Using CSS.

Either inside your <head> tag (the #search means "the element with an ID of search")

<style type="text/css">
    input#search
    {
        width: 20px;
        height: 20px;
    }
</style>

Or inline, in your <input> tag

<input type="submit" id="search" value="Search"  style="width: 20px; height: 20px;" />

did you register the component correctly? For recursive components, make sure to provide the "name" option

The high votes answer is right. You can checkout that you have applied different name for the components. But if the question is still not resolved, you can make sure that you have register the component only once.

_x000D_
_x000D_
components: {_x000D_
    IMContainer,_x000D_
    RightPanel_x000D_
},_x000D_
methods: {},_x000D_
components: {_x000D_
    IMContainer,_x000D_
    RightPanel_x000D_
}_x000D_
  
_x000D_
_x000D_
_x000D_

we always forget that we have register the component before

Subdomain on different host

You just need to add an "A" record in the DNS manager on Godaddy. In that "A" record put your IP from dreamhost.

I know this works since I'm doing the very same thing.

simple custom event

Events are pretty easy in C#, but the MSDN docs in my opinion make them pretty confusing. Normally, most documentation you see discusses making a class inherit from the EventArgs base class and there's a reason for that. However, it's not the simplest way to make events, and for someone wanting something quick and easy, and in a time crunch, using the Action type is your ticket.

Creating Events & Subscribing To Them

1. Create your event on your class right after your class declaration.

public event Action<string,string,string,string>MyEvent;

2. Create your event handler class method in your class.

private void MyEventHandler(string s1,string s2,string s3,string s4)
{
  Console.WriteLine("{0} {1} {2} {3}",s1,s2,s3,s4);
}

3. Now when your class is invoked, tell it to connect the event to your new event handler. The reason the += operator is used is because you are appending your particular event handler to the event. You can actually do this with multiple separate event handlers, and when an event is raised, each event handler will operate in the sequence in which you added them.

class Example
{
  public Example() // I'm a C# style class constructor
  {
    MyEvent += new Action<string,string,string,string>(MyEventHandler);
  }
}

4. Now, when you're ready, trigger (aka raise) the event somewhere in your class code like so:

MyEvent("wow","this","is","cool");

The end result when you run this is that the console will emit "wow this is cool". And if you changed "cool" with a date or a sequence, and ran this event trigger multiple times, you'd see the result come out in a FIFO sequence like events should normally operate.

In this example, I passed 4 strings. But you could change those to any kind of acceptable type, or used more or less types, or even remove the <...> out and pass nothing to your event handler.

And, again, if you had multiple custom event handlers, and subscribed them all to your event with the += operator, then your event trigger would have called them all in sequence.

Identifying Event Callers

But what if you want to identify the caller to this event in your event handler? This is useful if you want an event handler that reacts with conditions based on who's raised/triggered the event. There are a few ways to do this. Below are examples that are shown in order by how fast they operate:

Option 1. (Fastest) If you already know it, then pass the name as a literal string to the event handler when you trigger it.

Option 2. (Somewhat Fast) Add this into your class and call it from the calling method, and then pass that string to the event handler when you trigger it:

private static string GetCaller([System.Runtime.CompilerServices.CallerMemberName] string s = null) => s;

Option 3. (Least Fast But Still Fast) In your event handler when you trigger it, get the calling method name string with this:

string callingMethod = new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().ReflectedType.Name.Split('<', '>')[1];

Unsubscribing From Events

You may have a scenario where your custom event has multiple event handlers, but you want to remove one special one out of the list of event handlers. To do so, use the -= operator like so:

MyEvent -= MyEventHandler;

A word of minor caution with this, however. If you do this and that event no longer has any event handlers, and you trigger that event again, it will throw an exception. (Exceptions, of course, you can trap with try/catch blocks.)

Clearing All Events

Okay, let's say you're through with events and you don't want to process any more. Just set it to null like so:

MyEvent = null;

The same caution for Unsubscribing events is here, as well. If your custom event handler no longer has any events, and you trigger it again, your program will throw an exception.

How to find the first and second maximum number?

OK I found it.

=LARGE($E$4:$E$9;A12)

=large(array, k)

Array Required. The array or range of data for which you want to determine the k-th largest value.

K Required. The position (from the largest) in the array or cell range of data to return.

Remove carriage return from string

If you want to remove spaces at the beginning/end of a line too(common when shortening html) you can try:

string.Join("",input.Split('\n','\r').Select(s=>s.Trim()))

Else use the simple Replace Marc suggested.

How to increase font size in NeatBeans IDE?

press alt and scroll down or up to change the size

Abort a git cherry-pick?

For me, the only way to reset the failed cherry-pick-attempt was

git reset --hard HEAD

Asp.net 4.0 has not been registered

Open:

Start Menu
-> Programs
-> Microsoft Visual Studio 2010
-> Visual Studio Tools
-> Visual Studio Command Prompt (2010)

Run in command prompt:

aspnet_regiis -i

Make sure it is run at administrator, check that the title starts with Administrator:

enter image description here

Why are unnamed namespaces used and what are their benefits?

Unnamed namespace limits access of class,variable,function and objects to the file in which it is defined. Unnamed namespace functionality is similar to static keyword in C/C++.
static keyword limits access of global variable and function to the file in which they are defined.
There is difference between unnamed namespace and static keyword because of which unnamed namespace has advantage over static. static keyword can be used with variable, function and objects but not with user defined class.
For example:

static int x;  // Correct 

But,

static class xyz {/*Body of class*/} //Wrong
static structure {/*Body of structure*/} //Wrong

But same can be possible with unnamed namespace. For example,

 namespace {
           class xyz {/*Body of class*/}
           static structure {/*Body of structure*/}
  } //Correct

ggplot with 2 y axes on each side and different scales

For me the tricky part was figuring out the transformation function between the two axis. I used myCurveFit for that.

> dput(combined_80_8192 %>% filter (time > 270, time < 280))
structure(list(run = c(268L, 268L, 268L, 268L, 268L, 268L, 268L, 
268L, 268L, 268L, 263L, 263L, 263L, 263L, 263L, 263L, 263L, 263L, 
263L, 263L, 269L, 269L, 269L, 269L, 269L, 269L, 269L, 269L, 269L, 
269L, 261L, 261L, 261L, 261L, 261L, 261L, 261L, 261L, 261L, 261L, 
267L, 267L, 267L, 267L, 267L, 267L, 267L, 267L, 267L, 267L, 265L, 
265L, 265L, 265L, 265L, 265L, 265L, 265L, 265L, 265L, 266L, 266L, 
266L, 266L, 266L, 266L, 266L, 266L, 266L, 266L, 262L, 262L, 262L, 
262L, 262L, 262L, 262L, 262L, 262L, 262L, 264L, 264L, 264L, 264L, 
264L, 264L, 264L, 264L, 264L, 264L, 260L, 260L, 260L, 260L, 260L, 
260L, 260L, 260L, 260L, 260L), repetition = c(8L, 8L, 8L, 8L, 
8L, 8L, 8L, 8L, 8L, 8L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 5L, 5L, 
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 
6L, 6L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 
4L, 4L, 4L, 4L, 4L, 4L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L
), module = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "scenario.node[0].nicVLCTail.phyVLC", class = "factor"), 
    configname = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L), .Label = "Road-Vlc", class = "factor"), packetByteLength = c(8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L
    ), numVehicles = c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L
    ), dDistance = c(80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 
    80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 
    80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 
    80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 
    80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 
    80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 
    80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 
    80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 
    80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L), time = c(270.166006903445, 
    271.173853699836, 272.175873251122, 273.177524313334, 274.182946177105, 
    275.188959464989, 276.189675339937, 277.198250244799, 278.204619457189, 
    279.212562800009, 270.164199199177, 271.168527215152, 272.173072994958, 
    273.179210429715, 274.184351047337, 275.18980754378, 276.194816792995, 
    277.198598277809, 278.202398083519, 279.210634593917, 270.210674322891, 
    271.212395107473, 272.218871923292, 273.219060500457, 274.220486359614, 
    275.22401452372, 276.229646658839, 277.231060448138, 278.240407241942, 
    279.2437126347, 270.283554249858, 271.293168593832, 272.298574288769, 
    273.304413221348, 274.306272082517, 275.309023049011, 276.317805897347, 
    277.324403550028, 278.332855848701, 279.334046374594, 270.118608539613, 
    271.127947700074, 272.133887145863, 273.135726000491, 274.135994529981, 
    275.136563912708, 276.140120735361, 277.144298344151, 278.146885137621, 
    279.147552358659, 270.206015567272, 271.214618077209, 272.216566814903, 
    273.225435592582, 274.234014573683, 275.242949179958, 276.248417809711, 
    277.248800670023, 278.249750333404, 279.252926560188, 270.217182684494, 
    271.218357511397, 272.224698488895, 273.231112784327, 274.238740508457, 
    275.242715184122, 276.249053562718, 277.250325509798, 278.258488063493, 
    279.261141590137, 270.282904173953, 271.284689544638, 272.294220723234, 
    273.299749415592, 274.30628880553, 275.312075103126, 276.31579134717, 
    277.321905523606, 278.326305136748, 279.333056502253, 270.258991527456, 
    271.260224091407, 272.270076810133, 273.27052037648, 274.274119348094, 
    275.280808254502, 276.286353887245, 277.287064312339, 278.294444793276, 
    279.296772014594, 270.333066283904, 271.33877455992, 272.345842319903, 
    273.350858180493, 274.353972278505, 275.360454510107, 276.365088896161, 
    277.369166956941, 278.372571708911, 279.38017503079), distanceToTx = c(80.255266401689, 
    80.156059067023, 79.98823695539, 79.826647129071, 79.76678667135, 
    79.788239825292, 79.734539327997, 79.74766421514, 79.801243848241, 
    79.765920888341, 80.255266401689, 80.15850240049, 79.98823695539, 
    79.826647129071, 79.76678667135, 79.788239825292, 79.735078924078, 
    79.74766421514, 79.801243848241, 79.764622734914, 80.251248121732, 
    80.146436869316, 79.984682320466, 79.82292012342, 79.761908518748, 
    79.796988776281, 79.736920997657, 79.745038376718, 79.802638836686, 
    79.770029970452, 80.243475525691, 80.127918207499, 79.978303140866, 
    79.816259117883, 79.749322030693, 79.809916018889, 79.744456560867, 
    79.738655068783, 79.788697533211, 79.784288359619, 80.260412958482, 
    80.168426829066, 79.992034911214, 79.830845773284, 79.7756751763, 
    79.778156038931, 79.732399593756, 79.752769548846, 79.799967731078, 
    79.757585110481, 80.251248121732, 80.146436869316, 79.984682320466, 
    79.822062073459, 79.75884601899, 79.801590491435, 79.738335109094, 
    79.74347007248, 79.803215965043, 79.771471198955, 80.250257298678, 
    80.146436869316, 79.983831684476, 79.822062073459, 79.75884601899, 
    79.801590491435, 79.738335109094, 79.74347007248, 79.803849157574, 
    79.771471198955, 80.243475525691, 80.130180105198, 79.978303140866, 
    79.816881283718, 79.749322030693, 79.80984572883, 79.744456560867, 
    79.738655068783, 79.790548644175, 79.784288359619, 80.246349000313, 
    80.137056554491, 79.980581246037, 79.818924707937, 79.753176142361, 
    79.808777040341, 79.741609845588, 79.740770913572, 79.796316397253, 
    79.777593733292, 80.238796415443, 80.119021911134, 79.974810568944, 
    79.814065350562, 79.743657315504, 79.810146783217, 79.749945098869, 
    79.737122584544, 79.781650522348, 79.791554933936), headerNoError = c(0.99999999989702, 
    0.9999999999981, 0.99999999999946, 0.9999999928026, 0.99999873265475, 
    0.77080141574964, 0.99007491438593, 0.99994396605059, 0.45588747062284, 
    0.93484381262491, 0.99999999989702, 0.99999999999816, 0.99999999999946, 
    0.9999999928026, 0.99999873265475, 0.77080141574964, 0.99008458785106, 
    0.99994396605059, 0.45588747062284, 0.93480223051707, 0.99999999989735, 
    0.99999999999789, 0.99999999999946, 0.99999999287551, 0.99999876302649, 
    0.46903147501117, 0.98835168988253, 0.99994427085086, 0.45235035271542, 
    0.93496741877335, 0.99999999989803, 0.99999999999781, 0.99999999999948, 
    0.99999999318224, 0.99994254156311, 0.46891362282273, 0.93382613917348, 
    0.99994594904099, 0.93002915596843, 0.93569767251247, 0.99999999989658, 
    0.99999999998074, 0.99999999999946, 0.99999999272802, 0.99999871586781, 
    0.76935240919896, 0.99002587758346, 0.99999881589732, 0.46179415706093, 
    0.93417422376389, 0.99999999989735, 0.99999999999789, 0.99999999999946, 
    0.99999999289347, 0.99999876940486, 0.46930769326427, 0.98837353639905, 
    0.99994447154714, 0.16313586712094, 0.93500824170148, 0.99999999989744, 
    0.99999999999789, 0.99999999999946, 0.99999999289347, 0.99999876940486, 
    0.46930769326427, 0.98837353639905, 0.99994447154714, 0.16330039178981, 
    0.93500824170148, 0.99999999989803, 0.99999999999781, 0.99999999999948, 
    0.99999999316541, 0.99994254156311, 0.46794586553266, 0.93382613917348, 
    0.99994594904099, 0.9303627789484, 0.93569767251247, 0.99999999989778, 
    0.9999999999978, 0.99999999999948, 0.99999999311433, 0.99999878195152, 
    0.47101897739483, 0.93368891853679, 0.99994556595217, 0.7571113417265, 
    0.93553999975802, 0.99999999998191, 0.99999999999784, 0.99999999999971, 
    0.99999891129658, 0.99994309267792, 0.46510628979591, 0.93442584181035, 
    0.99894450514543, 0.99890078483692, 0.76933812306423), receivedPower_dbm = c(-93.023492290586, 
    -92.388378035287, -92.205716340607, -93.816400586752, -95.023489422885, 
    -100.86308557253, -98.464763536915, -96.175707680373, -102.06189538385, 
    -99.716653422746, -93.023492290586, -92.384760627397, -92.205716340607, 
    -93.816400586752, -95.023489422885, -100.86308557253, -98.464201120719, 
    -96.175707680373, -102.06189538385, -99.717150021506, -93.022927803442, 
    -92.404017215549, -92.204561341714, -93.814319484729, -95.016990717792, 
    -102.01669022332, -98.558088145955, -96.173817001483, -102.07406915124, 
    -99.71517574876, -93.021813165972, -92.409586309743, -92.20229160243, 
    -93.805335867418, -96.184419849593, -102.01709540787, -99.728735187547, 
    -96.163233028048, -99.772547164798, -99.706399753853, -93.024204617071, 
    -92.745813384859, -92.206884754512, -93.818508150122, -95.027018807793, 
    -100.87000577258, -98.467607232407, -95.005311380324, -102.04157607608, 
    -99.724619517, -93.022927803442, -92.404017215549, -92.204561341714, 
    -93.813803344588, -95.015606885523, -102.0157405687, -98.556982278361, 
    -96.172566862738, -103.21871579865, -99.714687230796, -93.022787428238, 
    -92.404017215549, -92.204274688493, -93.813803344588, -95.015606885523, 
    -102.0157405687, -98.556982278361, -96.172566862738, -103.21784988098, 
    -99.714687230796, -93.021813165972, -92.409950613665, -92.20229160243, 
    -93.805838770576, -96.184419849593, -102.02042267497, -99.728735187547, 
    -96.163233028048, -99.768774335378, -99.706399753853, -93.022228914406, 
    -92.411048503835, -92.203136463155, -93.807357409082, -95.012865008237, 
    -102.00985717796, -99.730352912911, -96.165675535906, -100.92744056572, 
    -99.708301333236, -92.735781110993, -92.408137395049, -92.119533319039, 
    -94.982938427575, -96.181073124017, -102.03018610927, -99.721633629806, 
    -97.32940323644, -97.347613268692, -100.87007386786), snr = c(49.848348091678, 
    57.698190927109, 60.17669971462, 41.529809724535, 31.452202106925, 
    8.1976890851341, 14.240447804094, 24.122884195464, 6.2202875499406, 
    10.674183333671, 49.848348091678, 57.746270018264, 60.17669971462, 
    41.529809724535, 31.452202106925, 8.1976890851341, 14.242292077376, 
    24.122884195464, 6.2202875499406, 10.672962852322, 49.854827699773, 
    57.49079026127, 60.192705735317, 41.549715223147, 31.499301851462, 
    6.2853718719014, 13.937702343688, 24.133388256416, 6.2028757927148, 
    10.677815810561, 49.867624820879, 57.417115267867, 60.224172277442, 
    41.635752021705, 24.074540962859, 6.2847854917092, 10.644529778044, 
    24.19227425387, 10.537686730745, 10.699414795917, 49.84017267426, 
    53.139646558768, 60.160512118809, 41.509660845114, 31.42665220053, 
    8.1846370024428, 14.231126423354, 31.584125885363, 6.2494585568733, 
    10.654622041348, 49.854827699773, 57.49079026127, 60.192705735317, 
    41.55465351989, 31.509340361646, 6.2867464196657, 13.941251828322, 
    24.140336174865, 4.765718874642, 10.679016976694, 49.856439162736, 
    57.49079026127, 60.196678846453, 41.55465351989, 31.509340361646, 
    6.2867464196657, 13.941251828322, 24.140336174865, 4.7666691818074, 
    10.679016976694, 49.867624820879, 57.412299088098, 60.224172277442, 
    41.630930975211, 24.074540962859, 6.279972363168, 10.644529778044, 
    24.19227425387, 10.546845071479, 10.699414795917, 49.862851240855, 
    57.397787176282, 60.212457625018, 41.61637603957, 31.529239767749, 
    6.2952688513108, 10.640565481982, 24.178672145334, 8.0771089950663, 
    10.694731030907, 53.262541905639, 57.43627424514, 61.382796189332, 
    31.747253311549, 24.093100244121, 6.2658701281075, 10.661949889074, 
    18.495227442305, 18.417839037171, 8.1845086722809), frameId = c(15051, 
    15106, 15165, 15220, 15279, 15330, 15385, 15452, 15511, 15566, 
    15019, 15074, 15129, 15184, 15239, 15298, 15353, 15412, 15471, 
    15526, 14947, 14994, 15057, 15112, 15171, 15226, 15281, 15332, 
    15391, 15442, 14971, 15030, 15085, 15144, 15203, 15262, 15321, 
    15380, 15435, 15490, 14915, 14978, 15033, 15092, 15147, 15198, 
    15257, 15312, 15371, 15430, 14975, 15034, 15089, 15140, 15195, 
    15254, 15313, 15368, 15427, 15478, 14987, 15046, 15105, 15160, 
    15215, 15274, 15329, 15384, 15447, 15506, 14943, 15002, 15061, 
    15116, 15171, 15230, 15285, 15344, 15399, 15454, 14971, 15026, 
    15081, 15136, 15195, 15258, 15313, 15368, 15423, 15478, 15039, 
    15094, 15149, 15204, 15263, 15314, 15369, 15428, 15487, 15546
    ), packetOkSinr = c(0.99999999314881, 0.9999999998736, 0.99999999996428, 
    0.99999952114066, 0.99991568416005, 3.00628034688444e-08, 
    0.51497487795954, 0.99627877136019, 0, 0.011303253101957, 
    0.99999999314881, 0.99999999987726, 0.99999999996428, 0.99999952114066, 
    0.99991568416005, 3.00628034688444e-08, 0.51530974419663, 
    0.99627877136019, 0, 0.011269851265775, 0.9999999931708, 
    0.99999999985986, 0.99999999996428, 0.99999952599145, 0.99991770469509, 
    0, 0.45861812482641, 0.99629897628155, 0, 0.011403119534097, 
    0.99999999321568, 0.99999999985437, 0.99999999996519, 0.99999954639936, 
    0.99618434878558, 0, 0.010513119213425, 0.99641022914441, 
    0.00801687746446111, 0.012011103529927, 0.9999999931195, 
    0.99999999871861, 0.99999999996428, 0.99999951617905, 0.99991456738049, 
    2.6525298291169e-08, 0.51328066587104, 0.9999212220316, 0, 
    0.010777054258914, 0.9999999931708, 0.99999999985986, 0.99999999996428, 
    0.99999952718674, 0.99991812902805, 0, 0.45929307038653, 
    0.99631228046814, 0, 0.011436292559188, 0.99999999317629, 
    0.99999999985986, 0.99999999996428, 0.99999952718674, 0.99991812902805, 
    0, 0.45929307038653, 0.99631228046814, 0, 0.011436292559188, 
    0.99999999321568, 0.99999999985437, 0.99999999996519, 0.99999954527918, 
    0.99618434878558, 0, 0.010513119213425, 0.99641022914441, 
    0.00821047996950475, 0.012011103529927, 0.99999999319919, 
    0.99999999985345, 0.99999999996519, 0.99999954188106, 0.99991896371849, 
    0, 0.010410830482692, 0.996384831822, 9.12484388049251e-09, 
    0.011877185067536, 0.99999999879646, 0.9999999998562, 0.99999999998077, 
    0.99992756868677, 0.9962208785486, 0, 0.010971897073662, 
    0.93214999078663, 0.92943956665979, 2.64925478221656e-08), 
    snir = c(49.848348091678, 57.698190927109, 60.17669971462, 
    41.529809724535, 31.452202106925, 8.1976890851341, 14.240447804094, 
    24.122884195464, 6.2202875499406, 10.674183333671, 49.848348091678, 
    57.746270018264, 60.17669971462, 41.529809724535, 31.452202106925, 
    8.1976890851341, 14.242292077376, 24.122884195464, 6.2202875499406, 
    10.672962852322, 49.854827699773, 57.49079026127, 60.192705735317, 
    41.549715223147, 31.499301851462, 6.2853718719014, 13.937702343688, 
    24.133388256416, 6.2028757927148, 10.677815810561, 49.867624820879, 
    57.417115267867, 60.224172277442, 41.635752021705, 24.074540962859, 
    6.2847854917092, 10.644529778044, 24.19227425387, 10.537686730745, 
    10.699414795917, 49.84017267426, 53.139646558768, 60.160512118809, 
    41.509660845114, 31.42665220053, 8.1846370024428, 14.231126423354, 
    31.584125885363, 6.2494585568733, 10.654622041348, 49.854827699773, 
    57.49079026127, 60.192705735317, 41.55465351989, 31.509340361646, 
    6.2867464196657, 13.941251828322, 24.140336174865, 4.765718874642, 
    10.679016976694, 49.856439162736, 57.49079026127, 60.196678846453, 
    41.55465351989, 31.509340361646, 6.2867464196657, 13.941251828322, 
    24.140336174865, 4.7666691818074, 10.679016976694, 49.867624820879, 
    57.412299088098, 60.224172277442, 41.630930975211, 24.074540962859, 
    6.279972363168, 10.644529778044, 24.19227425387, 10.546845071479, 
    10.699414795917, 49.862851240855, 57.397787176282, 60.212457625018, 
    41.61637603957, 31.529239767749, 6.2952688513108, 10.640565481982, 
    24.178672145334, 8.0771089950663, 10.694731030907, 53.262541905639, 
    57.43627424514, 61.382796189332, 31.747253311549, 24.093100244121, 
    6.2658701281075, 10.661949889074, 18.495227442305, 18.417839037171, 
    8.1845086722809), ookSnirBer = c(8.8808636558081e-24, 3.2219795637026e-27, 
    2.6468895519653e-28, 3.9807779074715e-20, 1.0849324265615e-15, 
    2.5705217057696e-05, 4.7313805615763e-08, 1.8800438086075e-12, 
    0.00021005320203921, 1.9147343768384e-06, 8.8808636558081e-24, 
    3.0694773489537e-27, 2.6468895519653e-28, 3.9807779074715e-20, 
    1.0849324265615e-15, 2.5705217057696e-05, 4.7223753038869e-08, 
    1.8800438086075e-12, 0.00021005320203921, 1.9171738578051e-06, 
    8.8229427230445e-24, 3.9715925056443e-27, 2.6045198111088e-28, 
    3.9014083702734e-20, 1.0342658440386e-15, 0.00019591630514278, 
    6.4692014108683e-08, 1.8600094209271e-12, 0.0002140067535655, 
    1.9074922485477e-06, 8.7096574467175e-24, 4.2779443633862e-27, 
    2.5231916788231e-28, 3.5761615214425e-20, 1.9750692814982e-12, 
    0.0001960392878411, 1.9748966344895e-06, 1.7515881895994e-12, 
    2.2078334799411e-06, 1.8649940680806e-06, 8.954486301678e-24, 
    3.2021085732779e-25, 2.690441113724e-28, 4.0627628846548e-20, 
    1.1134484878561e-15, 2.6061691733331e-05, 4.777159157954e-08, 
    9.4891388749738e-16, 0.00020359398491544, 1.9542110660398e-06, 
    8.8229427230445e-24, 3.9715925056443e-27, 2.6045198111088e-28, 
    3.8819641115984e-20, 1.0237769828158e-15, 0.00019562832342849, 
    6.4455095380046e-08, 1.8468752030971e-12, 0.0010099091367628, 
    1.9051035165106e-06, 8.8085966897635e-24, 3.9715925056443e-27, 
    2.594108048185e-28, 3.8819641115984e-20, 1.0237769828158e-15, 
    0.00019562832342849, 6.4455095380046e-08, 1.8468752030971e-12, 
    0.0010088638355194, 1.9051035165106e-06, 8.7096574467175e-24, 
    4.2987746909572e-27, 2.5231916788231e-28, 3.593647329558e-20, 
    1.9750692814982e-12, 0.00019705170257492, 1.9748966344895e-06, 
    1.7515881895994e-12, 2.1868296425817e-06, 1.8649940680806e-06, 
    8.7517439682173e-24, 4.3621551072316e-27, 2.553168170837e-28, 
    3.6469582463164e-20, 1.0032983660212e-15, 0.00019385229409318, 
    1.9830820164805e-06, 1.7760568361323e-12, 2.919419915209e-05, 
    1.8741284335866e-06, 2.8285944348148e-25, 4.1960751547207e-27, 
    7.8468215407139e-29, 8.0407329049747e-16, 1.9380328071065e-12, 
    0.00020004849911333, 1.9393279417733e-06, 5.9354475879597e-10, 
    6.4258355913627e-10, 2.6065221215415e-05), ookSnrBer = c(8.8808636558081e-24, 
    3.2219795637026e-27, 2.6468895519653e-28, 3.9807779074715e-20, 
    1.0849324265615e-15, 2.5705217057696e-05, 4.7313805615763e-08, 
    1.8800438086075e-12, 0.00021005320203921, 1.9147343768384e-06, 
    8.8808636558081e-24, 3.0694773489537e-27, 2.6468895519653e-28, 
    3.9807779074715e-20, 1.0849324265615e-15, 2.5705217057696e-05, 
    4.7223753038869e-08, 1.8800438086075e-12, 0.00021005320203921, 
    1.9171738578051e-06, 8.8229427230445e-24, 3.9715925056443e-27, 
    2.6045198111088e-28, 3.9014083702734e-20, 1.0342658440386e-15, 
    0.00019591630514278, 6.4692014108683e-08, 1.8600094209271e-12, 
    0.0002140067535655, 1.9074922485477e-06, 8.7096574467175e-24, 
    4.2779443633862e-27, 2.5231916788231e-28, 3.5761615214425e-20, 
    1.9750692814982e-12, 0.0001960392878411, 1.9748966344895e-06, 
    1.7515881895994e-12, 2.2078334799411e-06, 1.8649940680806e-06, 
    8.954486301678e-24, 3.2021085732779e-25, 2.690441113724e-28, 
    4.0627628846548e-20, 1.1134484878561e-15, 2.6061691733331e-05, 
    4.777159157954e-08, 9.4891388749738e-16, 0.00020359398491544, 
    1.9542110660398e-06, 8.8229427230445e-24, 3.9715925056443e-27, 
    2.6045198111088e-28, 3.8819641115984e-20, 1.0237769828158e-15, 
    0.00019562832342849, 6.4455095380046e-08, 1.8468752030971e-12, 
    0.0010099091367628, 1.9051035165106e-06, 8.8085966897635e-24, 
    3.9715925056443e-27, 2.594108048185e-28, 3.8819641115984e-20, 
    1.0237769828158e-15, 0.00019562832342849, 6.4455095380046e-08, 
    1.8468752030971e-12, 0.0010088638355194, 1.9051035165106e-06, 
    8.7096574467175e-24, 4.2987746909572e-27, 2.5231916788231e-28, 
    3.593647329558e-20, 1.9750692814982e-12, 0.00019705170257492, 
    1.9748966344895e-06, 1.7515881895994e-12, 2.1868296425817e-06, 
    1.8649940680806e-06, 8.7517439682173e-24, 4.3621551072316e-27, 
    2.553168170837e-28, 3.6469582463164e-20, 1.0032983660212e-15, 
    0.00019385229409318, 1.9830820164805e-06, 1.7760568361323e-12, 
    2.919419915209e-05, 1.8741284335866e-06, 2.8285944348148e-25, 
    4.1960751547207e-27, 7.8468215407139e-29, 8.0407329049747e-16, 
    1.9380328071065e-12, 0.00020004849911333, 1.9393279417733e-06, 
    5.9354475879597e-10, 6.4258355913627e-10, 2.6065221215415e-05
    )), class = "data.frame", row.names = c(NA, -100L), .Names = c("run", 
"repetition", "module", "configname", "packetByteLength", "numVehicles", 
"dDistance", "time", "distanceToTx", "headerNoError", "receivedPower_dbm", 
"snr", "frameId", "packetOkSinr", "snir", "ookSnirBer", "ookSnrBer"
))

Finding the transformation function

  1. y1 --> y2 This function is used to transform the data of the secondary y axis to be "normalized" according to the first y axis

enter image description here

transformation function: f(y1) = 0.025*x + 2.75


  1. y2 --> y1 This function is used to transform the break points of the first y axis to the values of the second y axis. Note that the axis are swapped now.

enter image description here

transformation function: f(y1) = 40*x - 110


Plotting

Note how the transformation functions are used in the ggplot call to transform the data "on-the-fly"

ggplot(data=combined_80_8192 %>% filter (time > 270, time < 280), aes(x=time) ) +
  stat_summary(aes(y=receivedPower_dbm ), fun.y=mean, geom="line", colour="black") +
  stat_summary(aes(y=packetOkSinr*40 - 110 ), fun.y=mean, geom="line", colour="black", position = position_dodge(width=10)) +
  scale_x_continuous() +
  scale_y_continuous(breaks = seq(-0,-110,-10), "y_first", sec.axis=sec_axis(~.*0.025+2.75, name="y_second") ) 

The first stat_summary call is the one that sets the base for the first y axis. The second stat_summary call is called to transform the data. Remember that all of the data will take as base the first y axis. So that data needs to be normalized for the first y axis. To do that I use the transformation function on the data: y=packetOkSinr*40 - 110

Now to transform the second axis I use the opposite function within the scale_y_continuous call: sec.axis=sec_axis(~.*0.025+2.75, name="y_second").

enter image description here

Get characters after last / in url

$str = basename($url);

How do I convert dmesg timestamp to custom date format?

So KevZero requested a less kludgy solution, so I came up with the following:

sed -r 's#^\[([0-9]+\.[0-9]+)\](.*)#echo -n "[";echo -n $(date --date="@$(echo "$(grep btime /proc/stat|cut -d " " -f 2)+\1" | bc)" +"%c");echo -n "]";echo -n "\2"#e'

Here's an example:

$ dmesg|tail | sed -r 's#^\[([0-9]+\.[0-9]+)\](.*)#echo -n "[";echo -n $(date --date="@$(echo "$(grep btime /proc/stat|cut -d " " -f 2)+\1" | bc)" +"%c");echo -n "]";echo -n "\2"#e'
[2015-12-09T04:29:20 COT] cfg80211:   (57240000 KHz - 63720000 KHz @ 2160000 KHz), (N/A, 0 mBm), (N/A)
[2015-12-09T04:29:23 COT] wlp3s0: authenticate with dc:9f:db:92:d3:07
[2015-12-09T04:29:23 COT] wlp3s0: send auth to dc:9f:db:92:d3:07 (try 1/3)
[2015-12-09T04:29:23 COT] wlp3s0: authenticated
[2015-12-09T04:29:23 COT] wlp3s0: associate with dc:9f:db:92:d3:07 (try 1/3)
[2015-12-09T04:29:23 COT] wlp3s0: RX AssocResp from dc:9f:db:92:d3:07 (capab=0x431 status=0 aid=6)
[2015-12-09T04:29:23 COT] wlp3s0: associated
[2015-12-09T04:29:56 COT] thinkpad_acpi: EC reports that Thermal Table has changed
[2015-12-09T04:29:59 COT] i915 0000:00:02.0: BAR 6: [??? 0x00000000 flags 0x2] has bogus alignment
[2015-12-09T05:00:52 COT] thinkpad_acpi: EC reports that Thermal Table has changed

If you want it to perform a bit better, put the timestamp from proc into a variable instead :)

how to create insert new nodes in JsonNode?

I've recently found even more interesting way to create any ValueNode or ContainerNode (Jackson v2.3).

ObjectNode node = JsonNodeFactory.instance.objectNode();

Why is setState in reactjs Async instead of Sync?

You can call a function after the state value has updated:

this.setState({foo: 'bar'}, () => { 
    // Do something here. 
});

Also, if you have lots of states to update at once, group them all within the same setState:

Instead of:

this.setState({foo: "one"}, () => {
    this.setState({bar: "two"});
});

Just do this:

this.setState({
    foo: "one",
    bar: "two"
});

How to checkout in Git by date?

Looks like you need something along the lines of this: Git checkout based on date

In other words, you use rev-list to find the commit and then use checkout to actually get it.

If you don't want to lose your staged changes, the easiest thing would be to create a new branch and commit them to that branch. You can always switch back and forth between branches.

Edit: The link is down, so here's the command:

git checkout `git rev-list -n 1 --before="2009-07-27 13:37" master`

How to fill color in a cell in VBA?

You need to use cell.Text = "#N/A" instead of cell.Value = "#N/A". The error in the cell is actually just text stored in the cell.

creating a table in ionic

This should probably be a comment, however, I don't have enough reputation to comment.

I suggest you really use the table (HTML) instead of ion-row and ion-col. Things will not look nice when one of the cell's content is too long.

One worse case looks like this:

| 10 | 20 | 30 | 40 |
| 1 | 2 | 3100 | 41 |

Higher fidelity example fork from @jpoveda

CSS "and" and "or"

Just in case if any one is stuck like me. After going though the post and some hit and trial this worked for me.

input:not([type="checkbox"])input:not([type="radio"])

Lazy Loading vs Eager Loading

// Using LINQ and just referencing p.Employer will lazy load
// I am not at a computer but I know I have lazy loaded in one
// query with a single query call like below.
List<Person> persons = new List<Person>();
using(MyDbContext dbContext = new MyDbContext())
{
    persons = (
        from p in dbcontext.Persons
        select new Person{
            Name = p.Name,
            Email = p.Email,
            Employer = p.Employer
        }).ToList();
}

Getting current device language in iOS?

Swift

To get current language of device

NSLocale.preferredLanguages()[0] as String

To get application language

NSBundle.mainBundle().preferredLocalizations[0] as NSString

Note:

It fetches the language that you have given in CFBundleDevelopmentRegion of info.plist

if CFBundleAllowMixedLocalizations is true in info.plist then first item of CFBundleLocalizations in info.plist is returned

How to set "style=display:none;" using jQuery's attr method?

You can use the jquery attr() method to achieve the setting of teh attribute and the method removeAttr() to delete the attribute for your element msform As seen in the code

$('#msform').attr('style', 'display:none;');


$('#msform').removeAttr('style');

How do I create a MessageBox in C#?

In the System.Windows.Forms class, you can find more on the MSDN page for this here. Among other things you can control the message box text, title, default button, and icons. Since you didn't specify, if you are trying to do this in a webpage you should look at triggering the javascript alert("my message"); or confirm("my question"); functions.

jQuery: print_r() display equivalent?

Look at this: http://phpjs.org/functions/index and find for print_r or use console.log() with firebug.

JavaScript backslash (\) in variables is causing an error

The jsfiddle link to where i tried out your query http://jsfiddle.net/A8Dnv/1/ its working fine @Imrul as mentioned you are using C# on server side and you dont mind that either: http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape.aspx

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

Here is a possible solution:

From your first script, call your second script with the following line:

wscript.exe invis.vbs run.bat %*

Actually, you are calling a vbs script with:

  • the [path]\name of your script
  • all the other arguments needed by your script (%*)

Then, invis.vbs will call your script with the Windows Script Host Run() method, which takes:

  • intWindowStyle : 0 means "invisible windows"
  • bWaitOnReturn : false means your first script does not need to wait for your second script to finish

Here is invis.vbs:

set args = WScript.Arguments
num = args.Count

if num = 0 then
    WScript.Echo "Usage: [CScript | WScript] invis.vbs aScript.bat <some script arguments>"
    WScript.Quit 1
end if

sargs = ""
if num > 1 then
    sargs = " "
    for k = 1 to num - 1
        anArg = args.Item(k)
        sargs = sargs & anArg & " "
    next
end if

Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.Run """" & WScript.Arguments(0) & """" & sargs, 0, False

How do I change the background color of the ActionBar of an ActionBarActivity using XML?

getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.TabColor)));

color.xml file:

<resources> <color name="TabColor">#11FF00</color> </resources>`

MySQL search and replace some text in a field

In my experience, the fastest method is

UPDATE table_name SET field = REPLACE(field, 'foo', 'bar') WHERE field LIKE '%foo%';

The INSTR() way is the second-fastest and omitting the WHERE clause altogether is slowest, even if the column is not indexed.

How to Logout of an Application Where I Used OAuth2 To Login With Google?

Overview of OAuth: Is the User Who He/She Says He/She is?:

I'm not sure if you used OAuth to login to Stack Overflow, like the "Login with Google" option, but when you use this feature, Stack Overflow is simply asking Google if it knows who you are:

"Yo Google, this Vinesh fella claims that [email protected] is him, is that true?"

If you're logged in already, Google will say YES. If not, Google will say:

"Hang on a sec Stack Overflow, I'll authenticate this fella and if he can enter the right password for his Google account, then it's him".

When you enter your Google password, Google then tells Stack Overflow you are who you say you are, and Stack Overflow logs you in.

When you logout of your app, you're logging out of your app:

Here's where developers new to OAuth sometimes get a little confused... Google and Stack Overflow, Assembla, Vinesh's-very-cool-slick-webapp, are all different entities, and Google knows nothing about your account on Vinesh's cool webapp, and vice versa, aside from what's exposed via the API you're using to access profile information.

When your user logs out, he or she isn't logging out of Google, he/she is logging out of your app, or Stack Overflow, or Assembla, or whatever web application used Google OAuth to authenticate the user.

In fact, I can log out of all of my Google accounts and still be logged into Stack Overflow. Once your app knows who the user is, that person can log out of Google. Google is no longer needed.

With that said, what you're asking to do is log the user out of a service that really doesn't belong to you. Think about it like this: As a user, how annoyed do you think I would be if I logged into 5 different services with my Google account, then the first time I logged out of one of them, I have to login to my Gmail account again because that app developer decided that, when I log out of his application, I should also be logged out of Google? That's going to get old really fast. In short, you really don't want to do this...

Yeh yeh, whatever, I still want to log the user out Of Google, just tell me how do I do this?

With that said, if you still do want to log a user out of Google, and realize that you may very well be disrupting their workflow, you could dynamically build the logout url from one of their Google services logout button, and then invoke that using an img element or a script tag:

<script type="text/javascript" 
    src="https://mail.google.com/mail/u/0/?logout&hl=en" />

OR

<img src="https://mail.google.com/mail/u/0/?logout&hl=en" />

OR

window.location = "https://mail.google.com/mail/u/0/?logout&hl=en";

If you redirect your user to the logout page, or invoke it from an element that isn't cross-domain restricted, the user will be logged out of Google.

Note that this does not necessarily mean the user will be logged out of your application, only Google. :)

Summary:

What's important for you to keep in mind is that, when you logout of your app, you don't need to make the user re-enter a password. That's the whole point! It authenticates against Google so the user doesn't have to enter his or her password over and over and over again in each web application he or she uses. It takes some getting used to, but know that, as long as the user is logged into Google, your app doesn't need to worry about whether or not the user is who he/she says he/she is.

I have the same implementation in a project as you do, using the Google Profile information with OAuth. I tried the very same thing you're looking to try, and it really started making people angry when they had to login to Google over and over again, so we stopped logging them out of Google. :)

Eloquent Collection: Counting and Detect Empty

When using ->get() you cannot simply use any of the below:

if (empty($result)) { }
if (!$result) { }
if ($result) { }

Because if you dd($result); you'll notice an instance of Illuminate\Support\Collection is always returned, even when there are no results. Essentially what you're checking is $a = new stdClass; if ($a) { ... } which will always return true.

To determine if there are any results you can do any of the following:

if ($result->first()) { } 
if (!$result->isEmpty()) { }
if ($result->count()) { }
if (count($result)) { }

You could also use ->first() instead of ->get() on the query builder which will return an instance of the first found model, or null otherwise. This is useful if you need or are expecting only one result from the database.

$result = Model::where(...)->first();
if ($result) { ... }

Notes / References

Bonus Information

The Collection and the Query Builder differences can be a bit confusing to newcomers of Laravel because the method names are often the same between the two. For that reason it can be confusing to know what one you’re working on. The Query Builder essentially builds a query until you call a method where it will execute the query and hit the database (e.g. when you call certain methods like ->all() ->first() ->lists() and others). Those methods also exist on the Collection object, which can get returned from the Query Builder if there are multiple results. If you're not sure what class you're actually working with, try doing var_dump(User::all()) and experimenting to see what classes it's actually returning (with help of get_class(...)). I highly recommend you check out the source code for the Collection class, it's pretty simple. Then check out the Query Builder and see the similarities in function names and find out when it actually hits the database.

What is context in _.each(list, iterator, [context])?

The context parameter just sets the value of this in the iterator function.

var someOtherArray = ["name","patrick","d","w"];

_.each([1, 2, 3], function(num) { 
    // In here, "this" refers to the same Array as "someOtherArray"

    alert( this[num] ); // num is the value from the array being iterated
                        //    so this[num] gets the item at the "num" index of
                        //    someOtherArray.
}, someOtherArray);

Working Example: http://jsfiddle.net/a6Rx4/

It uses the number from each member of the Array being iterated to get the item at that index of someOtherArray, which is represented by this since we passed it as the context parameter.

If you do not set the context, then this will refer to the window object.

Can I use if (pointer) instead of if (pointer != NULL)?

"Is it safe..?" is a question about the language standard and the generated code.

"Is is a good practice?" is a question about how well the statement is understood by any arbitrary human reader of the statement. If you are asking this question, it suggests that the "safe" version is less clear to future readers and writers.

Read Post Data submitted to ASP.Net Form

Read the Request.Form NameValueCollection and process your logic accordingly:

NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
  userName = nvc["txtUserName"];
}

if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
  password = nvc["txtPassword"];
}

//Process login
CheckLogin(userName, password);

... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.

Apache redirect to another port

Just use a Reverse Proxy in your apache configuration (directly):

ProxyPass /foo http://foo.example.com/bar
ProxyPassReverse /foo http://foo.example.com/bar

Look here for apache documentation of how to use the mod

best way to create object

There's not really a best way. Both are quite the same, unless you want to do some additional processing using the parameters passed to the constructor during initialization or if you want to ensure a coherent state just after calling the constructor. If it is the case, prefer the first one.

But for readability/maintainability reasons, avoid creating constructors with too many parameters.

In this case, both will do.

What is an ORM, how does it work, and how should I use one?

An ORM (Object Relational Mapper) is a piece/layer of software that helps map your code Objects to your database.

Some handle more aspects than others...but the purpose is to take some of the weight of the Data Layer off of the developer's shoulders.

Here's a brief clip from Martin Fowler (Data Mapper):

Patterns of Enterprise Application Architecture Data Mappers

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

Within the Visual Studio:

1) Remove your aspx.designer.cs file

2) Right click on your aspx file and select "Convert to Web Application" This should add the aspx.designer.cs back and up to date.

If you get an error saying:

"Generation of designer file failed: The method or operation is not implemented."

Try close Visual Studio and then reopen your project and do step number two again

How to generate aspx.designer.cs in visual studio?

Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

the short term solution is to use the default iis host and port normally 120.0.0.1 and 80 respectively. However am still looking for a more versatile solution.

Is there a Java equivalent or methodology for the typedef keyword in C++?

As others have mentioned before,
There is no typedef mechanism in Java.
I also do not support "fake classes" in general, but there should not be a general strict rule of thumb here:
If your code for example uses over and over and over a "generic based type" for example:

Map<String, List<Integer>> 

You should definitely consider having a subclass for that purpose.
Another approach one can consider, is for example to have in your code a deceleration like:

//@Alias Map<String, List<Integer>>  NameToNumbers;

And then use in your code NameToNumbers and have a pre compiler task (ANT/Gradle/Maven) to process and generate relevant java code.
I know that to some of the readers of this answer this might sound strange, but this is how many frameworks implemented "annotations" prior to JDK 5, this is what project lombok is doing and other frameworks.

JavaScript dictionary with names

An object technically is a dictionary.

var myMappings = {
    mykey1: 'myValue',
    mykey2: 'myValue'
};

var myVal = myMappings['myKey1'];

alert(myVal); // myValue

You can even loop through one.

for(var key in myMappings) {
    var myVal = myMappings[key];
    alert(myVal);
}

There is no reason whatsoever to reinvent the wheel. And of course, assignment goes like:

myMappings['mykey3'] = 'my value';

And ContainsKey:

if (myMappings.hasOwnProperty('myKey3')) {
    alert('key already exists!');
}

I suggest you follow this: http://javascriptissexy.com/how-to-learn-javascript-properly/

How do I convert an existing callback API to promises?

When you have a few functions that take a callback and you want them to return a promise instead you can use this function to do the conversion.

function callbackToPromise(func){

    return function(){

        // change this to use what ever promise lib you are using
        // In this case i'm using angular $q that I exposed on a util module

        var defered = util.$q.defer();

        var cb = (val) => {
            defered.resolve(val);
        }

        var args = Array.prototype.slice.call(arguments);
        args.push(cb);    
        func.apply(this, args);

        return defered.promise;
    }
}

I can't install intel HAXM

I faced this problem.I got the solution too.It will work.

Step 1: Go to your BIOS settings and check that INTERNET VIRTUAL TECHNOLOGY is Enabled or Disabled.

And make sure HYPER V is disabled. To disable it : a)Go to Control Panel b)Click on Programs(Uninstall a Program) c)Then click on Turn Windows features on or off , then look for HYPER-V and untick it. And Restart. If disabled then enable it.

Step 2: Try to install Intel HAXM now and restart. If It shows same problem again. go to Step 3.

Step 3: You have to disable Digitally Signed Enforcement. To disable it permanently you have to make sure that Secure Boot option is disabled in your system.

How to check ?

Answer is given in the following link. I found it in Internet.[Thanks whoever made that blog]

link : http://www.windowspasswordsrecovery.com/win8-tips/how-to-disable-uefi-secure-boot-in-windows-8-1-8.html

Step 4: Now restart again.

To disable driver signature enforcement permanently in Windows 10, you need to do the following:

1.Open an elevated command prompt instance.
2.Type/paste the following text:

     `bcdedit.exe /set nointegritychecks on`

or Windows 10

     `bcedit.exe -set loadoptions DISABLE_INTEGRITY_CHECKS`

Windows 10 disable driver signature enforcement

Restart Windows 10.

*If you somehow want to enable it again:

1.Type/paste the following text:

     `bcdedit.exe /set nointegritychecks off`

How to get Domain name from URL using jquery..?

This worked for me.

http://tech-blog.maddyzone.com/javascript/get-current-url-javascript-jquery

$(location).attr('host');                        www.test.com:8082
$(location).attr('hostname');                    www.test.com
$(location).attr('port');                        8082
$(location).attr('protocol');                    http:
$(location).attr('pathname');                    index.php
$(location).attr('href');                        http://www.test.com:8082/index.php#tab2
$(location).attr('hash');                       #tab2
$(location).attr('search');                     ?foo=123

How do I specify a password to 'psql' non-interactively?

  • in one line:

    export PGPASSWORD='password'; psql -h 'server name' -U 'user name' -d 'base name' -c 'command'
    

    with command a sql command such as "select * from schema.table"

  • or more readable:

    export PGPASSWORD='password'
    psql -h 'server name' -U 'user name' -d 'base name' \
         -c 'command' (eg. "select * from schema.table")
    

How can I combine hashes in Perl?

This is an old question, but comes out high in my Google search for 'perl merge hashes' - and yet it does not mention the very helpful CPAN module Hash::Merge

Invert colors of an image in CSS or JavaScript

Can be done in major new broswers using the code below

.img {
    -webkit-filter:invert(100%);
     filter:progid:DXImageTransform.Microsoft.BasicImage(invert='1');
}

However, if you want it to work across all browsers you need to use Javascript. Something like this gist will do the job.

how to check if input field is empty

use .val(), it will return the value of the <input>

$("#spa").val().length > 0

And you had a typo, length not lenght.

Prevent line-break of span element

If you only need to prevent line-breaks on space characters, you can use &nbsp; entities between words:

No&nbsp;line&nbsp;break

instead of

<span style="white-space:nowrap">No line break</span>

Error message 'java.net.SocketException: socket failed: EACCES (Permission denied)'

If you are using an emulator for testing then you must use <uses-permission android:name="android.permission.INTERNET" />only and ignore <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />.It's work for me.

Find package name for Android apps to use Intent to launch Market app from web

Here are easy way to get app's full package. we can use astro file manager app. You can get it on android market. Astro app manager show us app's full package.

How to launch another aspx web page upon button click?

If you'd like to use Code Behind, may I suggest the following solution for an asp:button -

ASPX Page

<asp:Button ID="btnRecover" runat="server" Text="Recover" OnClick="btnRecover_Click" />

Code Behind

    protected void btnRecover_Click(object sender, EventArgs e)
    {
        var recoveryId = Guid.Parse(lbRecovery.SelectedValue);
        var url = string.Format("{0}?RecoveryId={1}", @"../Recovery.aspx", vehicleId);

        // Response.Redirect(url); // Old way

        Response.Write("<script> window.open( '" + url + "','_blank' ); </script>");
        Response.End();
    }

Creation timestamp and last update timestamp with Hibernate and MySQL

We had a similar situation. We were using Mysql 5.7.

CREATE TABLE my_table (
        ...
      updated_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    );

This worked for us.

How are cookies passed in the HTTP protocol?

The server sends the following in its response header to set a cookie field.

Set-Cookie:name=value

If there is a cookie set, then the browser sends the following in its request header.

Cookie:name=value

See the HTTP Cookie article at Wikipedia for more information.

Join/Where with LINQ and Lambda

I've done something like this;

var certificationClass = _db.INDIVIDUALLICENSEs
    .Join(_db.INDLICENSECLAsses,
        IL => IL.LICENSE_CLASS,
        ILC => ILC.NAME,
        (IL, ILC) => new { INDIVIDUALLICENSE = IL, INDLICENSECLAsse = ILC })
    .Where(o => 
        o.INDIVIDUALLICENSE.GLOBALENTITYID == "ABC" &&
        o.INDIVIDUALLICENSE.LICENSE_TYPE == "ABC")
    .Select(t => new
        {
            value = t.PSP_INDLICENSECLAsse.ID,
            name = t.PSP_INDIVIDUALLICENSE.LICENSE_CLASS,                
        })
    .OrderBy(x => x.name);

Is there a way to make AngularJS load partials in the beginning and not at when needed?

If you wrap each template in a script tag, eg:

<script id="about.html" type="text/ng-template">
<div>
    <h3>About</h3>
    This is the About page
    Its cool!
</div>
</script>

Concatenate all templates into 1 big file. If using Visual Studio 2013, download Web essentials - it adds a right click menu to create an HTML Bundle.

Add the code that this guy wrote to change the angular $templatecache service - its only a small piece of code and it works: Vojta Jina's Gist

Its the $http.get that should be changed to use your bundle file:

allTplPromise = $http.get('templates/templateBundle.min.html').then(

Your routes templateUrl should look like this:

        $routeProvider.when(
            "/about", {
                controller: "",
                templateUrl: "about.html"
            }
        );

Convert string[] to int[] in one line of code using LINQ

var list = arr.Select(i => Int32.Parse(i));

How to find prime numbers between 0 - 100?

Here is a way to test if number is prime number.

function isPrime(numb){
  if (numb % 2 == 0) return false;
  for (var i=3; i<= Math.sqrt(numb); i = i + 2) {
    if (numb % i == 0) {
     return false;
    }
  }
  return true;
}

Windows batch files: .bat vs .cmd?

everything working in a batch should work in a cmd; cmd provides some extensions for controlling the environment. also, cmd is executed by in new cmd interpreter and thus should be faster (not noticeable on short files) and stabler as bat runs under the NTVDM emulated 16bit environment

Difference between if () { } and if () : endif;

It all depends, personally I prefer the traditional syntax with echos and plenty of indentations, since it's just so much easier to read.

<?php
    if($something){
        doThis();
    }else{
        echo '<h1>Title</h1>
            <p>This is a paragraph</p>
            <p>and another paragraph</p>';
    }
?>

I agree alt syntax is cleaner with the different end clauses, but I really have a hard time dealing with them without help from text-editor highlighting, and I'm just not used to seeing "condensed" code like this:

<?php if( $this->isEnabledViewSwitcher() ): ?>
<p class="view-mode">
    <?php $_modes = $this->getModes(); ?>
    <?php if($_modes && count($_modes)>1): ?>
    <label><?php echo $this->__('View as') ?>:</label>
    <?php foreach ($this->getModes() as $_code=>$_label): ?>
        <?php if($this->isModeActive($_code)): ?>
            <strong title="<?php echo $_label ?>" class="<?php echo strtolower($_code); ?>"><?php echo $_label ?></strong>&nbsp;
        <?php else: ?>
            <a href="<?php echo $this->getModeUrl($_code) ?>" title="<?php echo $_label ?>" class="<?php echo strtolower($_code); ?>"><?php echo $_label ?></a>&nbsp;
        <?php endif; ?>
    <?php endforeach; ?>
    <?php endif; ?>
</p>
<?php endif; ?>

Add space between cells (td) using css

cellspacing (distance between cells) parameter of the TABLE tag is precisely what you want. The disadvantage is it's one value, used both for x and y, you can't choose different spacing or padding vertically/horizontally. There is a CSS property too, but it's not widely supported.

How to convert a std::string to const char* or char*?

Use the .c_str() method for const char *.

You can use &mystring[0] to get a char * pointer, but there are a couple of gotcha's: you won't necessarily get a zero terminated string, and you won't be able to change the string's size. You especially have to be careful not to add characters past the end of the string or you'll get a buffer overrun (and probable crash).

There was no guarantee that all of the characters would be part of the same contiguous buffer until C++11, but in practice all known implementations of std::string worked that way anyway; see Does “&s[0]” point to contiguous characters in a std::string?.

Note that many string member functions will reallocate the internal buffer and invalidate any pointers you might have saved. Best to use them immediately and then discard.

Postgresql GROUP_CONCAT equivalent?

Since 9.0 this is even easier:

SELECT id, 
       string_agg(some_column, ',')
FROM the_table
GROUP BY id

reStructuredText tool support

Salvaging (and extending) the list from an old version of the Wikipedia page:

Documentation

Implementations

Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.

Python - Docutils

The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:

  • rst2html - from reStructuredText to HTML
  • rst2xml - from reStructuredText to XML
  • rst2latex - from reStructuredText to LaTeX
  • rst2odt - from reStructuredText to ODF Text (word processor) document.
  • rst2s5 - from reStructuredText to S5, a Simple Standards-based Slide Show System
  • rst2man - from reStructuredText to Man page

Haskell - Pandoc

Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.

There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),

  • POT truncates input rather more shortly. The POT user must render input in chunks that could be rendered whole by the ROR.
  • POT output lacks the helpful error messages displayed by the ROR (and generated by docutils)

Java - JRst

JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.

Scala - Laika

Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.

Perl

PHP

C#/.NET

Nim/C

The Nim compiler features the commands rst2htmland rst2tex which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:

  • rst - implements a reStructuredText parser
  • rstast - implements an AST for the reStructuredText parser
  • rstgen - implements a generator of HTML/Latex from reStructuredText

Other 3rd party converters

Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.

From reStructuredText

  • restview - This pip-installable python package requires docutils, which does the actual rendering. restview's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
    1. starts a small web server
    2. calls docutils to render your document(s) to HTML
    3. calls your device's browser to display the output HTML.
  • rst2pdf - from reStructuredText to PDF
  • rst2odp - from reStructuredText to ODF Presentation
  • rst2beamer - from reStructuredText to LaTeX beamer Presentation class
  • Wikir - from reStructuredText to a Google (and possibly other) Wiki formats
  • rst2qhc - Convert a collection of reStructuredText files into a Qt (toolkit) Help file and (optional) a Qt Help Project file

To reStructuredText

  • xml2rst is an XSLT script to convert Docutils internal XML representation (back) to reStructuredText
  • Pandoc (see above) can also convert from Markdown, HTML and LaTeX to reStructuredText
  • db2rst is a simple and limited DocBook to reStructuredText translator
  • pod2rst - convert .pod files to reStructuredText files

Extensions

Some projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.

Sphinx

The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.

rest2web

rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.

Pygments

Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.

Free Editors

While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.

Emacs

The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el

Vim

The vim-common package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:

Jed

There is a rst mode for the Jed programmers editor.

gedit

gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.

Geany

Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).

Leo

Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).

It also provides a way to preview the resulting HTML, in a "viewrendered" pane.

FTE

The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.

PyK

PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.

Eclipse

The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.

NoTex

NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.

Notepad++

Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.

Visual Studio Code

Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.

Dedicated reStructuredText Editors

Proprietary editors

Sublime Text

Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.

BBEdit / TextWrangler

BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.

TextMate

TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.

Intype

Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.

E Text Editor

E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.

PyCharm

PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).instant preview)

Wiki

here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:

MediaWiki

MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst> and </rst>.

MoinMoin

MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.

There is a reStructuredText Parser for MoinMoin.

Trac

Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.

This Wiki

This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.

rstiki

rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.

ikiwiki

Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.

Web Services

Sandbox

An Online reStructuredText editor can be used to play with the markup and see the results immediately.

Blogging frameworks

WordPress

WordPreSt reStructuredText plugin for WordPress. (PHP)

Zine

reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)

pelican

Pelican is a static blog generator that supports writing articles in ReST. (Python)

hyde

Hyde is a static website generator that supports ReST. (Python)

Acrylamid

Acrylamid is a static blog generator that supports writing articles in ReST. (Python)

Nikola

Nikola is a Static Site and Blog Generator that supports ReST. (Python)

ipsum genera

Ipsum genera is a static blog generator written in Nim.

Yozuch

Yozuch is a static blog generator written in Python.

More

twitter-bootstrap: how to get rid of underlined button text when hovering over a btn-group within an <a>-tag?

Bootstrap 4+

This is now easy to do in Bootstrap 4+

<a href="#" class="text-decoration-none">
    <!-- That is all -->
</a>

What's the syntax for mod in java

While it's possible to do a proper modulo by checking whether the value is negative and correct it if it is (the way many have suggested), there is a more compact solution.

(a % b + b) % b

This will first do the modulo, limiting the value to the -b -> +b range and then add b in order to ensure that the value is positive, letting the next modulo limit it to the 0 -> b range.

Note: If b is negative, the result will also be negative

If isset $_POST

Use !empty instead of isset. isset return true for $_POST because $_POST array is superglobal and always exists (set).

Or better use $_SERVER['REQUEST_METHOD'] == 'POST'

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

Lets assume you created a Ubuntu VM on your local machine. It's IP address is 192.168.1.104.

You login into VM, and installed Kubernetes. Then you created a pod where nginx image running on it.

1- If you want to access this nginx pod inside your VM, you will create a ClusterIP bound to that pod for example:

$ kubectl expose deployment nginxapp --name=nginxclusterip --port=80 --target-port=8080

Then on your browser you can type ip address of nginxclusterip with port 80, like:

http://10.152.183.2:80

2- If you want to access this nginx pod from your host machine, you will need to expose your deployment with NodePort. For example:

$ kubectl expose deployment nginxapp --name=nginxnodeport --port=80 --target-port=8080 --type=NodePort

Now from your host machine you can access to nginx like:

http://192.168.1.104:31865/

In my dashboard they appear as:

enter image description here

Below is a diagram shows basic relationship.

enter image description here

Python Decimals format

Here's a function that will do the trick:

def myformat(x):
    return ('%.2f' % x).rstrip('0').rstrip('.')

And here are your examples:

>>> myformat(1.00)
'1'
>>> myformat(1.20)
'1.2'
>>> myformat(1.23)
'1.23'
>>> myformat(1.234)
'1.23'
>>> myformat(1.2345)
'1.23'

Edit:

From looking at other people's answers and experimenting, I found that g does all of the stripping stuff for you. So,

'%.3g' % x

works splendidly too and is slightly different from what other people are suggesting (using '{0:.3}'.format() stuff). I guess take your pick.

SQL update fields of one table from fields of another one

You can use the non-standard FROM clause.

UPDATE b
SET column1 = a.column1,
  column2 = a.column2,
  column3 = a.column3
FROM a
WHERE a.id = b.id
AND b.id = 1

Error: Specified cast is not valid. (SqlManagerUI)

Sometimes it happens because of the version change like store 2012 db on 2008, so how to check it?

RESTORE VERIFYONLY FROM DISK = N'd:\yourbackup.bak'

if it gives error like:

Msg 3241, Level 16, State 13, Line 2 The media family on device 'd:\alibaba.bak' is incorrectly formed. SQL Server cannot process this media family. Msg 3013, Level 16, State 1, Line 2 VERIFY DATABASE is terminating abnormally.

Check it further:

RESTORE HEADERONLY FROM DISK = N'd:\yourbackup.bak'

BackupName is "* INCOMPLETE *", Position is "1", other fields are "NULL".

Means either your backup is corrupt or taken from newer version.

Can you put two conditions in an xslt test attribute?

Maybe this is a no-brainer for the xslt-professional, but for me at beginner/intermediate level, this got me puzzled. I wanted to do exactly the same thing, but I had to test a responsetime value from an xml instead of a plain number. Following this thread, I tried this:

<xsl:when test="responsetime/@value &gt;= 5000 and responsetime/@value &lt;= 8999"> 

which generated an error. This works:

<xsl:when test="number(responsetime/@value) &gt;= 5000 and number(responsetime/@value) &lt;= 8999">

Don't really understand why it doesn't work without number(), though. Could it be that without number() the value is treated as a string and you can't compare numbers with a string?

Anyway, hope this saves someone a lot of searching...

Best way to pretty print a hash

Use the answers above if you're printing to users.

If you only want to print it for yourself in console, I suggest using the pry gem instead of irb. Besides pretty printing, pry has a lot of other features as well (check railscast below)

gem install pry

And check this railscast:

http://railscasts.com/episodes/280-pry-with-rails

Meaning of Open hashing and Closed hashing

You have an array that is the "hash table".

In Open Hashing each cell in the array points to a list containg the collisions. The hashing has produced the same index for all items in the linked list.

In Closed Hashing you use only one array for everything. You store the collisions in the same array. The trick is to use some smart way to jump from collision to collision unitl you find what you want. And do this in a reproducible / deterministic way.

Bootstrap 3 - jumbotron background image effect

After inspecting the sample website you provided, I found that the author might achieve the effect by using a library called Stellar.js, take a look at the library site, cheers!

AngularJS $http, CORS and http authentication

For making a CORS request one must add headers to the request along with the same he needs to check of mode_header is enabled in Apache.

For enabling headers in Ubuntu:

sudo a2enmod headers

For php server to accept request from different origin use:

Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

Getting the SQL from a Django QuerySet

This middleware will output every SQL query to your console, with color highlighting and execution time, it's been invaluable for me in optimizing some tricky requests

http://djangosnippets.org/snippets/290/

Convert generic List/Enumerable to DataTable?

If you are using VB.NET then this class does the job.

Imports System.Reflection
''' <summary>
''' Convert any List(Of T) to a DataTable with correct column types and converts Nullable Type values to DBNull
''' </summary>

Public Class ConvertListToDataset

    Public Function ListToDataset(Of T)(ByVal list As IList(Of T)) As DataTable

        Dim dt As New DataTable()
        '/* Create the DataTable columns */
        For Each pi As PropertyInfo In GetType(T).GetProperties()
            If pi.PropertyType.IsValueType Then
                Debug.Print(pi.Name)
            End If
            If IsNothing(Nullable.GetUnderlyingType(pi.PropertyType)) Then
                dt.Columns.Add(pi.Name, pi.PropertyType)
            Else
                dt.Columns.Add(pi.Name, Nullable.GetUnderlyingType(pi.PropertyType))
            End If
        Next

        '/* Populate the DataTable with the values in the Items in List */
        For Each item As T In list
            Dim dr As DataRow = dt.NewRow()
            For Each pi As PropertyInfo In GetType(T).GetProperties()
                dr(pi.Name) = IIf(IsNothing(pi.GetValue(item)), DBNull.Value, pi.GetValue(item))
            Next
            dt.Rows.Add(dr)
        Next
        Return dt

    End Function

End Class

Sample random rows in dataframe

First make some data:

> df = data.frame(matrix(rnorm(20), nrow=10))
> df
           X1         X2
1   0.7091409 -1.4061361
2  -1.1334614 -0.1973846
3   2.3343391 -0.4385071
4  -0.9040278 -0.6593677
5   0.4180331 -1.2592415
6   0.7572246 -0.5463655
7  -0.8996483  0.4231117
8  -1.0356774 -0.1640883
9  -0.3983045  0.7157506
10 -0.9060305  2.3234110

Then select some rows at random:

> df[sample(nrow(df), 3), ]
           X1         X2
9  -0.3983045  0.7157506
2  -1.1334614 -0.1973846
10 -0.9060305  2.3234110

Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

Instead of using System.in and System.out directly, use the Console class - it allows you to display a prompt and read an entire line (thereby fixing your problem) of input in one call:

String address = System.console().readLine("Enter your Address: ");

How to check if an element of a list is a list (in Python)?

you can simply write:

for item,i in zip(your_list, range(len(your_list)):

    if type(item) == list:
        print(f"{item} at index {i} is a list")