Programs & Examples On #Wm paint

WM_PAINT is a central message in the classic Microsoft Windows API.

How do I disable text selection with CSS or JavaScript?

UPDATE January, 2017:

According to Can I use, the user-select is currently supported in all browsers except Internet Explorer 9 and earlier versions (but sadly still needs a vendor prefix).


All of the correct CSS variations are:

_x000D_
_x000D_
.noselect {_x000D_
  -webkit-touch-callout: none; /* iOS Safari */_x000D_
    -webkit-user-select: none; /* Safari */_x000D_
     -khtml-user-select: none; /* Konqueror HTML */_x000D_
       -moz-user-select: none; /* Firefox */_x000D_
        -ms-user-select: none; /* Internet Explorer/Edge */_x000D_
            user-select: none; /* Non-prefixed version, currently_x000D_
                                  supported by Chrome and Opera */_x000D_
}
_x000D_
<p>_x000D_
  Selectable text._x000D_
</p>_x000D_
<p class="noselect">_x000D_
  Unselectable text._x000D_
</p>
_x000D_
_x000D_
_x000D_


Note that it's a non-standard feature (i.e. not a part of any specification). It is not guaranteed to work everywhere, and there might be differences in implementation among browsers and in the future browsers can drop support for it.


More information can be found in Mozilla Developer Network documentation.

.htaccess redirect www to non-www with SSL/HTTPS

www to non www with https

RewriteEngine on

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

RewriteCond %{ENV:HTTPS} !on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Create stacked barplot where each stack is scaled to sum to 100%

prop.table is a nice friendly way of obtaining proportions of tables.

m <- matrix(1:4,2)

 m
     [,1] [,2]
[1,]    1    3
[2,]    2    4

Leaving margin blank gives you proportions of the whole table

 prop.table(m, margin=NULL)
     [,1] [,2]
[1,]  0.1  0.3
[2,]  0.2  0.4

Giving it 1 gives you row proportions

 prop.table(m, 1)
      [,1]      [,2]
[1,] 0.2500000 0.7500000
[2,] 0.3333333 0.6666667

And 2 is column proportions

 prop.table(m, 2)
          [,1]      [,2]
[1,] 0.3333333 0.4285714
[2,] 0.6666667 0.5714286

Does Java support default parameter values?

Unfortunately, yes.

void MyParameterizedFunction(String param1, int param2, bool param3=false) {}

could be written in Java 1.5 as:

void MyParameterizedFunction(String param1, int param2, Boolean... params) {
    assert params.length <= 1;
    bool param3 = params.length > 0 ? params[0].booleanValue() : false;
}

But whether or not you should depend on how you feel about the compiler generating a

new Boolean[]{}

for each call.

For multiple defaultable parameters:

void MyParameterizedFunction(String param1, int param2, bool param3=false, int param4=42) {}

could be written in Java 1.5 as:

void MyParameterizedFunction(String param1, int param2, Object... p) {
    int l = p.length;
    assert l <= 2;
    assert l < 1 || Boolean.class.isInstance(p[0]);
    assert l < 2 || Integer.class.isInstance(p[1]);
    bool param3 = l > 0 && p[0] != null ? ((Boolean)p[0]).booleanValue() : false;
    int param4 = l > 1 && p[1] != null ? ((Integer)p[1]).intValue() : 42;
}

This matches C++ syntax, which only allows defaulted parameters at the end of the parameter list.

Beyond syntax, there is a difference where this has run time type checking for passed defaultable parameters and C++ type checks them during compile.

Setting the number of map tasks and reduce tasks

Number of map task depends on File size, If you want n number of Map, divide the file size by n as follows:

conf.set("mapred.max.split.size", "41943040"); // maximum split file size in bytes
conf.set("mapred.min.split.size", "20971520"); // minimum split file size in bytes

Pass a password to ssh in pure bash

You can not specify the password from the command line but you can do either using ssh keys or using sshpass as suggested by John C. or using a expect script.

To use sshpass, you need to install it first. Then

sshpass -f <(printf '%s\n' your_password) ssh user@hostname

instead of using sshpass -p your_password. As mentioned by Charles Duffy in the comments, it is safer to supply the password from a file or from a variable instead of from command line.

BTW, a little explanation for the <(command) syntax. The shell executes the command inside the parentheses and replaces the whole thing with a file descriptor, which is connected to the command's stdout. You can find more from this answer https://unix.stackexchange.com/questions/156084/why-does-process-substitution-result-in-a-file-called-dev-fd-63-which-is-a-pipe

Explanation of JSONB introduced by PostgreSQL

  • hstore is more of a "wide column" storage type, it is a flat (non-nested) dictionary of key-value pairs, always stored in a reasonably efficient binary format (a hash table, hence the name).
  • json stores JSON documents as text, performing validation when the documents are stored, and parsing them on output if needed (i.e. accessing individual fields); it should support the entire JSON spec. Since the entire JSON text is stored, its formatting is preserved.
  • jsonb takes shortcuts for performance reasons: JSON data is parsed on input and stored in binary format, key orderings in dictionaries are not maintained, and neither are duplicate keys. Accessing individual elements in the JSONB field is fast as it doesn't require parsing the JSON text all the time. On output, JSON data is reconstructed and initial formatting is lost.

IMO, there is no significant reason for not using jsonb once it is available, if you are working with machine-readable data.

Google Chrome form autofill and its yellow background

Solution here:

if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {
    $(window).load(function(){
        $('input:-webkit-autofill').each(function(){
            var text = $(this).val();
            var name = $(this).attr('name');
            $(this).after(this.outerHTML).remove();
            $('input[name=' + name + ']').val(text);
        });
    });
}

Batch Extract path and filename from a variable

if you want infos from the actual running batchfile, try this :

@echo off
set myNameFull=%0
echo myNameFull     %myNameFull%
set myNameShort=%~n0
echo myNameShort    %myNameShort%
set myNameLong=%~nx0
echo myNameLong     %myNameLong%
set myPath=%~dp0
echo myPath         %myPath%
set myLogfileWpath=%myPath%%myNameShort%.log
echo myLogfileWpath %myLogfileWpath%

more samples? C:> HELP CALL

%0 = parameter 0 = batchfile %1 = parameter 1 - 1st par. passed to batchfile... so you can try that stuff (e.g. "~dp") between 1st (e.g. "%") and last (e.g. "1") also for parameters

How do I revert all local changes in Git managed project to previous state?

If you want to revert changes made to your working copy, do this:

git checkout .

If you want to revert changes made to the index (i.e., that you have added), do this. Warning this will reset all of your unpushed commits to master!:

git reset

If you want to revert a change that you have committed, do this:

git revert <commit 1> <commit 2>

If you want to remove untracked files (e.g., new files, generated files):

git clean -f

Or untracked directories (e.g., new or automatically generated directories):

git clean -fd

How to get POSTed JSON in Flask?

Try to use force parameter...

request.get_json(force = True)

Pandas rename column by position?

You can do this:

df.rename(columns={ df.columns[1]: "whatever" })

MySQL date formats - difficulty Inserting a date

Looks like you've not encapsulated your string properly. Try this:

INSERT INTO custorder VALUES ('Kevin','yes'), STR_TO_DATE('1-01-2012', '%d-%m-%Y');

Alternatively, you can do the following but it is not recommended. Make sure that you use STR_TO-DATE it is because when you are developing web applications you have to explicitly convert String to Date which is annoying. Use first One.

INSERT INTO custorder VALUES ('Kevin','yes'), '2012-01-01';

I'm not confident that the above SQL is valid, however, and you may want to move the date part into the brackets. If you can provide the exact error you're getting, I might be able to more directly help with the issue.

How can I find an element by CSS class with XPath?

XPath has a contains-token function, specifically designed for this situation:

//div[contains-token(@class, 'Test')]

It's only supported in the latest version of XPath (3.1) so you'll need an up-to-date implementation.

How does a Breadth-First Search work when looking for Shortest Path?

I have wasted 3 days
ultimately solved a graph question
used for
finding shortest distance
using BFS

Want to share the experience.

When the (undirected for me) graph has
fixed distance (1, 6, etc.) for edges

#1
We can use BFS to find shortest path simply by traversing it
then, if required, multiply with fixed distance (1, 6, etc.)

#2
As noted above
with BFS
the very 1st time an adjacent node is reached, it is shortest path

#3
It does not matter what queue you use
   deque/queue(c++) or
   your own queue implementation (in c language)
   A circular queue is unnecessary

#4
Number of elements required for queue is N+1 at most, which I used
(dint check if N works)
here, N is V, number of vertices.

#5
Wikipedia BFS will work, and is sufficient.
    https://en.wikipedia.org/wiki/Breadth-first_search#Pseudocode

I have lost 3 days trying all above alternatives, verifying & re-verifying again and again above
they are not the issue.
(Try to spend time looking for other issues, if you dint find any issues with above 5).


More explanation from the comment below:

      A
     /  \
  B       C
 /\       /\
D  E     F  G

Assume above is your graph
graph goes downwards
For A, the adjacents are B & C
For B, the adjacents are D & E
For C, the adjacents are F & G

say, start node is A

  1. when you reach A, to, B & C the shortest distance to B & C from A is 1

  2. when you reach D or E, thru B, the shortest distance to A & D is 2 (A->B->D)

similarly, A->E is 2 (A->B->E)

also, A->F & A->G is 2

So, now instead of 1 distance between nodes, if it is 6, then just multiply the answer by 6
example,
if distance between each is 1, then A->E is 2 (A->B->E = 1+1)
if distance between each is 6, then A->E is 12 (A->B->E = 6+6)

yes, bfs may take any path
but we are calculating for all paths

if you have to go from A to Z, then we travel all paths from A to an intermediate I, and since there will be many paths we discard all but shortest path till I, then continue with shortest path ahead to next node J
again if there are multiple paths from I to J, we only take shortest one
example,
assume,
A -> I we have distance 5
(STEP) assume, I -> J we have multiple paths, of distances 7 & 8, since 7 is shortest
we take A -> J as 5 (A->I shortest) + 8 (shortest now) = 13
so A->J is now 13
we repeat now above (STEP) for J -> K and so on, till we get to Z

Read this part, 2 or 3 times, and draw on paper, you will surely get what i am saying, best of luck


IntelliJ does not show 'Class' when we right click and select 'New'

Most of the people already gave the answer but this one is just for making someone's life easier.

TL;DR

Screenshot of how to add test sources

You must add the test folder as source.

  1. Right click on java directory under test
  2. Mark it as Tests
  3. Add src/test/java in Test Source Folders

Thats it, IntelliJ will consider them as test source.

How is OAuth 2 different from OAuth 1?

Security of the OAuth 1.0 protocol (RFC 5849) relies on the assumption that a secret key embedded in a client application can be kept confidential. However, the assumption is naive.

In OAuth 2.0 (RFC 6749), such a naive client application is called a confidential client. On the other hand, a client application in an environment where it is difficult to keep a secret key confidential is called a public client. See 2.1. Client Types for details.

In that sense, OAuth 1.0 is a specification only for confidential clients.

"OAuth 2.0 and the Road to Hell" says that OAuth 2.0 is less secure, but there is no practical difference in security level between OAuth 1.0 clients and OAuth 2.0 confidential clients. OAuth 1.0 requires to compute signature, but it does not enhance security if it is already assured that a secret key on the client side can be kept confidential. Computing signature is just a cumbersome calculation without any practical security enhancement. I mean, compared to the simplicity that an OAuth 2.0 client connects to a server over TLS and just presents client_id and client_secret, it cannot be said that the cumbersome calculation is better in terms of security.

In addition, RFC 5849 (OAuth 1.0) does not mention anything about open redirectors while RFC 6749 (OAuth 2.0) does. That is, oauth_callback parameter of OAuth 1.0 can become a security hole.

Therefore, I don't think OAuth 1.0 is more secure than OAuth 2.0.


[April 14, 2016] Addition to clarify my point

OAuth 1.0 security relies on signature computation. A signature is computed using a secret key where a secret key is a shared key for HMAC-SHA1 (RFC 5849, 3.4.2) or a private key for RSA-SHA1 (RFC 5849, 3.4.3). Anyone who knows the secret key can compute the signature. So, if the secret key is compromised, complexity of signature computation is meaningless however complex it is.

This means OAuth 1.0 security relies not on the complexity and the logic of signature computation but merely on the confidentiality of a secret key. In other words, what is needed for OAuth 1.0 security is only the condition that a secret key can be kept confidential. This may sound extreme, but signature computation adds no security enhancement if the condition is already satisfied.

Likewise, OAuth 2.0 confidential clients rely on the same condition. If the condition is already satisfied, is there any problem in creating a secure connection using TLS and sending client_id and client_secret to an authorization server through the secured connection? Is there any big difference in security level between OAuth 1.0 and OAuth 2.0 confidential clients if both rely on the same condition?

I cannot find any good reason for OAuth 1.0 to blame OAuth 2.0. The fact is simply that (1) OAuth 1.0 is just a specification only for confidential clients and (2) OAuth 2.0 has simplified the protocol for confidential clients and supported public clients, too. Regardless of whether it is known well or not, smartphone applications are classified as public clients (RFC 6749, 9), which benefit from OAuth 2.0.

How to Find the Default Charset/Encoding in Java?

First, Latin-1 is the same as ISO-8859-1, so, the default was already OK for you. Right?

You successfully set the encoding to ISO-8859-1 with your command line parameter. You also set it programmatically to "Latin-1", but, that's not a recognized value of a file encoding for Java. See http://java.sun.com/javase/6/docs/technotes/guides/intl/encoding.doc.html

When you do that, looks like Charset resets to UTF-8, from looking at the source. That at least explains most of the behavior.

I don't know why OutputStreamWriter shows ISO8859_1. It delegates to closed-source sun.misc.* classes. I'm guessing it isn't quite dealing with encoding via the same mechanism, which is weird.

But of course you should always be specifying what encoding you mean in this code. I'd never rely on the platform default.

msvcr110.dll is missing from computer error while installing PHP

I had installed PHP in IIS7 on Windows Server 2008 R2 using the Web Platform Installer. It did not work out of the box. I had to install the Visual C++ Redistributable for VS 2012 Update 4 (32bit) as found here http://www.microsoft.com/en-us/download/details.aspx?id=30679 .

Delete all rows in an HTML table

If you have far fewer <th> rows than non-<th> rows, you could collect all the <th> rows into a string, remove the entire table, and then write <table>thstring</table> where the table used to be.

EDIT: Where, obviously, "thstring" is the html for all of the rows of <th>s.

Making view resize to its parent when added with addSubview

If you aren’t using Auto Layout, have you tried setting the child view’s autoresize mask? Try this:

myChildeView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
                                 UIViewAutoresizingFlexibleHeight);

Also, you may need to call

myParentView.autoresizesSubviews = YES;

to get the parent view to resize its subviews automatically when its frame changes.

If you’re still seeing the child view drawing outside of the parent view’s frame, there’s a good chance that the parent view is not clipping its contents. To fix that, call

myParentView.clipsToBounds = YES;

How to activate JMX on my JVM for access with jconsole?

I had this exact issue, and created a GitHub project for testing and figuring out the correct settings.

It contains a working Dockerfile with supporting scripts, and a simple docker-compose.yml for quick testing.

Get button click inside UITableViewCell

Following code might Help you.

I have taken UITableView with custom prototype cell class named UITableViewCell inside UIViewController.

So i have ViewController.h, ViewController.m and TableViewCell.h,TableViewCell.m

Here is the code for that:

ViewController.h

@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) IBOutlet UITableView *tblView;

@end

ViewController.m

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return (YourNumberOfRows);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *cellIdentifier = @"cell";

    __weak TableViewCell *cell = (TableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    if (indexPath.row==0) {
        [cell setDidTapButtonBlock:^(id sender)
         {
             // Your code here

         }];
    }    
    return cell;
}

Custom cell class :

TableViewCell.h

@interface TableViewCell : UITableViewCell

@property (copy, nonatomic) void (^didTapButtonBlock)(id sender);

@property (strong, nonatomic) IBOutlet UILabel *lblTitle;
@property (strong, nonatomic) IBOutlet UIButton *btnAction;

- (void)setDidTapButtonBlock:(void (^)(id sender))didTapButtonBlock;

@end

and

UITableViewCell.m

@implementation TableViewCell

- (void)awakeFromNib {
    // Initialization code
    [self.btnAction addTarget:self action:@selector(didTapButton:) forControlEvents:UIControlEventTouchUpInside];

}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}
- (void)didTapButton:(id)sender {
    if (self.didTapButtonBlock)
    {
        self.didTapButtonBlock(sender);
    }
}

Note: Here I have taken all UIControls using Storyboard.

Hope that can help you...!!!

How to view the Folder and Files in GAC?

Launch the program "Run" (Windows Vista/7/8: type it in the start menu search bar) and type: C:\windows\assembly\GAC_MSIL

Then move to the parent folder (Windows Vista/7/8: by clicking on it in the explorer bar) to see all the GAC files in a normal explorer window. You can now copy, add and remove files as everywhere else.

How can I make a UITextField move up when the keyboard is present - on starting to edit?

This piece of code will calculate how much need to move up based on the keyboard height and how deep the text field as gone. Remember to add delegate and inherit UITextFieldDelegate at your header.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_tbxUsername resignFirstResponder];
    [_tbxPassword resignFirstResponder];
}

- (void)textFieldDidBeginEditing:(UITextField *) textField
{
    [self animateTextField:textField up:YES];
}

- (void)textFieldDidEndEditing:(UITextField *) textField
{
    [self animateTextField:textField up:NO];
}

- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
    int animatedDistance;
    int moveUpValue = textField.frame.origin.y+ textField.frame.size.height;
    UIInterfaceOrientation orientation =
    [[UIApplication sharedApplication] statusBarOrientation];
    if (orientation == UIInterfaceOrientationPortrait ||
        orientation == UIInterfaceOrientationPortraitUpsideDown)
    {

        animatedDistance = 236-(460-moveUpValue-5);
    }
    else
    {
        animatedDistance = 182-(320-moveUpValue-5);
    }

    if(animatedDistance>0)
    {
        const int movementDistance = animatedDistance;
        const float movementDuration = 0.3f;
        int movement = (up ? -movementDistance : movementDistance);
        [UIView beginAnimations: nil context: nil];
        [UIView setAnimationBeginsFromCurrentState: YES];
        [UIView setAnimationDuration: movementDuration];
        self.view.frame = CGRectOffset(self.view.frame, 0, movement);
        [UIView commitAnimations];
    }
}

Delegate to add at ViewDidLoad

_tbxUsername.delegate = self;
_tbxPassword.delegate = self;

Detecting Browser Autofill

in 2020, this is what worked for me in chrome:

// wait 0.1 sec to execute action after detecting autofill
// check if input username is autofilled by browser
// enable "login" button for click to submit form
 $(window).on("load", function(){
       setTimeout(function(){

           if ($("#UserName").is("input:-webkit-autofill")) 
           $("#loginbtn").prop('disabled', false); 

      }, 100);
 });

Angular 5 ngHide ngShow [hidden] not working

If you can not use *ngif, [class.hide] works in angular 7. example:

<mat-select (selectionChange)="changeFilter($event.value)" multiple [(ngModel)]="selected">
          <mat-option *ngFor="let filter of gridOptions.columnDefs"
                      [class.hide]="filter.headerName=='Action'"  [value]="filter.field">{{filter.headerName}}</mat-option>
        </mat-select>

What are the proper permissions for an upload folder with PHP/Apache?

I would support the idea of creating a ftp group that will have the rights to upload. However, i don't think it is necessary to give 775 permission. 7 stands for read, write, execute. Normally you want to allow certain groups to read and write, but depending on the case, execute may not be necessary.

Make child visible outside an overflow:hidden parent

For others, if clearfix does not solve this for you, add margins to the non-floated sibling that is/are the same as the width(s) of the floated sibling(s).

Difference between clean, gradlew clean

You can also use

./gradlew clean build (Mac and Linux) -With ./

gradlew clean build (Windows) -Without ./

it removes build folder, as well configure your modules and then build your project.

i use it before release any new app on playstore.

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

How to auto adjust the <div> height according to content in it?

Set a height to the last placeholder div.

    <div class="row" style="height:30px;">
    <!--placeholder to make the whole block has valid auto height-->

In C#, how to check if a TCP port is available?

Thanks for this tip. I needed the same functionality but on the Server side to check if a Port was in use so I modified it to this code.

 private bool CheckAvailableServerPort(int port) {
    LOG.InfoFormat("Checking Port {0}", port);
    bool isAvailable = true;

    // Evaluate current system tcp connections. This is the same information provided
    // by the netstat command line application, just in .Net strongly-typed object
    // form.  We will look through the list, and if our port we would like to use
    // in our TcpClient is occupied, we will set isAvailable to false.
    IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
    IPEndPoint[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners();

    foreach (IPEndPoint endpoint in tcpConnInfoArray) {
        if (endpoint.Port == port) {
            isAvailable = false;
            break;
        }
    }

    LOG.InfoFormat("Port {0} available = {1}", port, isAvailable);

    return isAvailable;
}

How do I print bytes as hexadecimal?

I don't know of a better way than:

unsigned char byData[xxx]; 

int nLength = sizeof(byData) * 2;
char *pBuffer = new char[nLength + 1];
pBuffer[nLength] = 0;
for (int i = 0; i < sizeof(byData); i++)
{
    sprintf(pBuffer[2 * i], "%02X", byData[i]);
}

You can speed it up by using a Nibble to Hex method

unsigned char byData[xxx];

const char szNibbleToHex = { "0123456789ABCDEF" };

int nLength = sizeof(byData) * 2;
char *pBuffer = new char[nLength + 1];
pBuffer[nLength] = 0;
for (int i = 0; i < sizeof(byData); i++)
{
    // divide by 16
    int nNibble = byData[i] >> 4;
    pBuffer[2 * i]  = pszNibbleToHex[nNibble];

    nNibble = byData[i] & 0x0F;
    pBuffer[2 * i + 1]  = pszNibbleToHex[nNibble];

}

Left/Right float button inside div

You can use justify-content: space-between in .test like so:

_x000D_
_x000D_
.test {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  width: 20rem;_x000D_
  border: .1rem red solid;_x000D_
}
_x000D_
<div class="test">_x000D_
  <button>test</button>_x000D_
  <button>test</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_


For those who want to use Bootstrap 4 can use justify-content-between:

_x000D_
_x000D_
div {_x000D_
  width: 20rem;_x000D_
  border: .1rem red solid;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="d-flex justify-content-between">_x000D_
  <button>test</button>_x000D_
  <button>test</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

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

If you have this:

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

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

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

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

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

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

Selecting all three sub-classes: .x

RSA: Get exponent and modulus given a public key

I manage to find the answer for this solution, have to do javascript injection for this to install atob

const atob:any = require('atob');
asn1(pem: any){
      asn1parser.Enc.base64ToBuf = function (b64:any) {
    return asn1parser.Enc.binToBuf(atob(b64));
  };
  const dertest = asn1parser.PEM.parseBlock(pem).der;
   var hex = asn1parser.Enc.bufToHex(asn1parser.PEM.parseBlock(pem).der)
   var buf = asn1parser.ASN1.parse(dertest);
  var asn1 = JSON.stringify(asn1parser.ASN1.parse(dertest), asn1parser.ASN1._replacer, 2 );

How do I add a placeholder on a CharField in Django?

The other methods are all good. However, if you prefer to not specify the field (e.g. for some dynamic method), you can use this:

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['email'].widget.attrs['placeholder'] = self.fields['email'].label or '[email protected]'

It also allows the placeholder to depend on the instance for ModelForms with instance specified.

Find out time it took for a python script to complete execution

import sys
import timeit

start = timeit.default_timer()

#do some nice things...

stop = timeit.default_timer()
total_time = stop - start

# output running time in a nice format.
mins, secs = divmod(total_time, 60)
hours, mins = divmod(mins, 60)

sys.stdout.write("Total running time: %d:%d:%d.\n" % (hours, mins, secs))

Make a link use POST instead of GET

Instead using javascript, you could also use a label sending a hidden form. Very simple and small solution. The label can be anywhere in your html.

_x000D_
_x000D_
<form style="display: none" action="postUrl" method="post">_x000D_
  <button type="submit" id="button_to_link"> </button>_x000D_
</form>_x000D_
<label style="text-decoration: underline" for="button_to_link">  link that posts </label>
_x000D_
_x000D_
_x000D_

IntelliJ IDEA "cannot resolve symbol" and "cannot resolve method"

Most likely JDK configuration is not valid, try to remove and add the JDK again as I've described in the related question here.

Initializing C# auto-properties

In the default constructor (and any non-default ones if you have any too of course):

public foo() {
    Bar = "bar";
}

This is no less performant that your original code I believe, since this is what happens behind the scenes anyway.

Can an AJAX response set a cookie?

Also check that your server isn't setting secure cookies on a non http request. Just found out that my ajax request was getting a php session with "secure" set. Because I was not on https it was not sending back the session cookie and my session was getting reset on each ajax request.

Check if an element is present in a Bash array

As bash does not have a built-in value in array operator and the =~ operator or the [[ "${array[@]" == *"${item}"* ]] notation keep confusing me, I usually combine grep with a here-string:

colors=('black' 'blue' 'light green')
if grep -q 'black' <<< "${colors[@]}"
then
    echo 'match'
fi

Beware however that this suffers from the same false positives issue as many of the other answers that occurs when the item to search for is fully contained, but is not equal to another item:

if grep -q 'green' <<< "${colors[@]}"
then
    echo 'should not match, but does'
fi

If that is an issue for your use case, you probably won't get around looping over the array:

for color in "${colors[@]}"
do
    if [ "${color}" = 'green' ]
    then
        echo "should not match and won't"
        break
    fi
done

for color in "${colors[@]}"
do
    if [ "${color}" = 'light green' ]
    then
        echo 'match'
        break
    fi
done

Jenkins - How to access BUILD_NUMBER environment variable

For Groovy script in the Jenkinsfile using the $BUILD_NUMBER it works.

MySQL vs MongoDB 1000 reads

man,,, the answer is that you're basically testing PHP and not a database.

don't bother iterating the results, whether commenting out the print or not. there's a chunk of time.

   foreach ($cursor as $obj)
    {
        //echo $obj["thread_title"] . "<br><Br>";
    }

while the other chunk is spend yacking up a bunch of rand numbers.

function get_15_random_numbers()
{
    $numbers = array();
    for($i=1;$i<=15;$i++)
    {
        $numbers[] = mt_rand(1, 20000000) ;

    }
    return $numbers;
}

then theres a major difference b/w implode and in.

and finally what is going on here. looks like creating a connection each time, thus its testing the connection time plus the query time.

$m = new Mongo();

vs

$db = new AQLDatabase();

so your 101% faster might turn out to be 1000% faster for the underlying query stripped of jazz.

urghhh.

Maven dependency for Servlet 3.0 API?

The Apache Geronimo project provides a Servlet 3.0 API dependency on the Maven Central repo:

<dependency>
    <groupId>org.apache.geronimo.specs</groupId>
    <artifactId>geronimo-servlet_3.0_spec</artifactId>
    <version>1.0</version>
</dependency>

Access elements in json object like an array

The your seems a multi-array, not a JSON object.

If you want access the object like an array, you have to use some sort of key/value, such as:

var JSONObject = {
  "city": ["Blankaholm, "Gamleby"],
  "date": ["2012-10-23", "2012-10-22"],
  "description": ["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har.],
  "lat": ["57.586174","16.521841"], 
  "long": ["57.893162","16.406090"]
}

and access it with:

JSONObject.city[0] // => Blankaholm
JSONObject.date[1] // => 2012-10-22

and so on...

or

JSONObject['city'][0] // => Blankaholm
JSONObject['date'][1] // => 2012-10-22

and so on...

or, in last resort, if you don't want change your structure, you can do something like that:

var JSONObject = {
  "data": [
    ["Blankaholm, "Gamleby"],
    ["2012-10-23", "2012-10-22"],
    ["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har.],
    ["57.586174","16.521841"], 
    ["57.893162","16.406090"]
  ]
}

JSONObject.data[0][1] // => Gambleby

How to create JSON object Node.js

What I believe you're looking for is a way to work with arrays as object values:

var o = {} // empty Object
var key = 'Orientation Sensor';
o[key] = []; // empty Array, which you can push() values into


var data = {
    sampleTime: '1450632410296',
    data: '76.36731:3.4651554:0.5665419'
};
var data2 = {
    sampleTime: '1450632410296',
    data: '78.15431:0.5247617:-0.20050584'
};
o[key].push(data);
o[key].push(data2);

This is standard JavaScript and not something NodeJS specific. In order to serialize it to a JSON string you can use the native JSON.stringify:

JSON.stringify(o);
//> '{"Orientation Sensor":[{"sampleTime":"1450632410296","data":"76.36731:3.4651554:0.5665419"},{"sampleTime":"1450632410296","data":"78.15431:0.5247617:-0.20050584"}]}'

Store query result in a variable using in PL/pgSQL

As long as you are assigning a single variable, you can also use plain assignment in a plpgsql function:

name := (SELECT t.name from test_table t where t.id = x);

Or use SELECT INTO like @mu already provided.

This works, too:

name := t.name from test_table t where t.id = x;

But better use one of the first two, clearer methods, as @Pavel commented.

I shortened the syntax with a table alias additionally.
Update: I removed my code example and suggest to use IF EXISTS() instead like provided by @Pavel.

How do I invoke a Java method when given the method name as a string?

for me a pretty simple and fool proof way would be to simply make a method caller method like so:

public static object methodCaller(String methodName)
{
    if(methodName.equals("getName"))
        return className.getName();
}

then when you need to call the method simply put something like this

//calling a toString method is unnessary here, but i use it to have my programs to both rigid and self-explanitory 
System.out.println(methodCaller(methodName).toString()); 

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

_x000D_
_x000D_
<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Apache giving 403 forbidden errors

You can try disabling selinux and try once again using the following command

setenforce 0

Can I position an element fixed relative to parent?

first, set position: fixed and left: 50%, and second — now your start is a center and you can set new position with margin.

What is the Eclipse shortcut for "public static void main(String args[])"?

In Eclipse, select preferences.

In preferences, look for Java/Editor/Templates.

Here you will see a list of all of them. And you can even add your own.

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

The whole point of a class is that you create an instance, and that instance encapsulates a set of data. So it's wrong to say that your variables are global within the scope of the class: say rather that an instance holds attributes, and that instance can refer to its own attributes in any of its code (via self.whatever). Similarly, any other code given an instance can use that instance to access the instance's attributes - ie instance.whatever.

WPF Datagrid Get Selected Cell Value

I was in such situation .. and found This:

int ColumnIndex = DataGrid.CurrentColumn.DisplayIndex;
TextBlock CellContent = DataGrid.SelectedCells[ColumnIndex].Column.GetCellContent(DataGrid.SelectedItem);

And make sure to treat custom columns' templates

How to show data in a table by using psql command line interface?

Newer versions: (from 8.4 - mentioned in release notes)

TABLE mytablename;

Longer but works on all versions:

SELECT * FROM mytablename;

You may wish to use \x first if it's a wide table, for readability.

For long data:

SELECT * FROM mytable LIMIT 10;

or similar.

For wide data (big rows), in the psql command line client, it's useful to use \x to show the rows in key/value form instead of tabulated, e.g.

 \x
SELECT * FROM mytable LIMIT 10;

Note that in all cases the semicolon at the end is important.

What is difference between mutable and immutable String in java

When you say str, you should be careful what you mean:

  • do you mean the variable str?

  • or do you mean the object referenced by str?

In your StringBuffer example you are not altering the value of str, and in your String example you are not altering the state of the String object.

The most poignant way to experience the difference would be something like this:

static void change(String in) { 
  in = in + " changed";
}

static void change(StringBuffer in) {
  in.append(" changed");
}

public static void main(String[] args) {
   StringBuffer sb = new StringBuffer("value");
   String str = "value";
   change(sb);
   change(str);
   System.out.println("StringBuffer: "+sb);
   System.out.println("String: "+str);
}

MySQL: #126 - Incorrect key file for table

Came here searching for - "#1034 - Incorrect key file for table 'test'; try to repair it"

Seeing this caused by added a charset to an indexed Enum (might be the same with other fields) with Mysql 8.0.21.

CREATE TABLE `test` (
`enumVal` ENUM( 'val1' ) NOT NULL
) ENGINE = MYISAM;
ALTER TABLE `test` ADD INDEX ( `enumVal` );

ALTER TABLE  `test` CHANGE  `enumVal`  `enumVal` ENUM(  'val1') CHARACTER SET utf8 COLLATE utf8_bin NOT NULL;

Solution using is to drop the index before the alter.

ALTER TABLE `test` ADD INDEX ( `enumVal` );

How to get ER model of database from server with Workbench

I want to enhance Mr. Kamran Ali's answer with pictorial view.

Pictorial View is given step by step:

  1. Go to "Database" Menu option
  2. Select the "Reverse Engineer" option.

enter image description here

  1. A wizard will come. Select from "Stored Connection" and press "Next" button.

enter image description here

  1. Then "Next"..to.."Finish"

Enjoy :)

RuntimeWarning: invalid value encountered in divide

You are dividing by rr which may be 0.0. Check if rr is zero and do something reasonable other than using it in the denominator.

Show Current Location and Update Location in MKMapView in Swift

MyLocation is a Swift iOS Demo.

You can use this demo for the following:

  1. Show the current location.

  2. Choose other location: in this case stop tracking the location.

  3. Add a push pin to a MKMapView(iOS) when touching.

Tell Ruby Program to Wait some amount of time

Implementation of seconds/minutes/hours, which are rails methods. Note that implicit returns aren't needed, but they look cleaner, so I prefer them. I'm not sure Rails even has .days or if it goes further, but these are the ones I need.

class Integer
   def seconds
      return self
   end
   def minutes
      return self * 60
   end
   def hours
      return self * 3600
   end
   def days
      return self * 86400
   end
end

After this, you can do: sleep 5.seconds to sleep for 5 seconds. You can do sleep 5.minutes to sleep for 5 min. You can do sleep 5.hours to sleep for 5 hours. And finally, you can do sleep 5.days to sleep for 5 days... You can add any method that return the value of self * (amount of seconds in that timeframe). As an exercise, try implementing it for months!

Android, How can I Convert String to Date?

From String to Date

String dtStart = "2010-10-15T09:27:37Z";  
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
try {  
    Date date = format.parse(dtStart);  
    System.out.println(date);  
} catch (ParseException e) {
    e.printStackTrace();  
}

From Date to String

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
try {  
    Date date = new Date();  
    String dateTime = dateFormat.format(date);
    System.out.println("Current Date Time : " + dateTime); 
} catch (ParseException e) {
    e.printStackTrace();  
}

How to show all of columns name on pandas dataframe?

What worked for me was the following:

pd.options.display.max_seq_items = None

You can also set it to an integer larger than your number of columns.

How to modify a CSS display property from JavaScript?

It should be document.getElementById("hidden").style.display = "block"; not document.getElementById["hidden"].style.display = "block";


EDIT due to author edit:

Why are you using a <div> here? Just add an ID to the table element and add a hidden style to it. E.g. <td id="hidden" style="display:none" class="depot_table_left">

Limit the height of a responsive image with css

I set the below 3 styles to my img tag

max-height: 500px;
height: 70%;
width: auto;

What it does that for desktop screen img doesn't grow beyond 500px but for small mobile screens, it will shrink to 70% of the outer container. Works like a charm.

It also works width property.

Ansible: create a user with sudo privileges

To create a user with sudo privileges is to put the user into /etc/sudoers, or make the user a member of a group specified in /etc/sudoers. And to make it password-less is to additionally specify NOPASSWD in /etc/sudoers.

Example of /etc/sudoers:

## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL

## Allows people in group wheel to run all commands
%wheel  ALL=(ALL)       ALL

## Same thing without a password
%wheel  ALL=(ALL)       NOPASSWD: ALL

And instead of fiddling with /etc/sudoers file, we can create a new file in /etc/sudoers.d/ directory since this directory is included by /etc/sudoers by default, which avoids the possibility of breaking existing sudoers file, and also eliminates the dependency on the content inside of /etc/sudoers.

To achieve above in Ansible, refer to the following:

- name: sudo without password for wheel group
  copy:
    content: '%wheel ALL=(ALL:ALL) NOPASSWD:ALL'
    dest: /etc/sudoers.d/wheel_nopasswd
    mode: 0440

You may replace %wheel with other group names like %sudoers or other user names like deployer.

How to "flatten" a multi-dimensional array to simple one in PHP?

If you're okay with loosing array keys, you may flatten a multi-dimensional array using a recursive closure as a callback that utilizes array_values(), making sure that this callback is a parameter for array_walk(), as follows.

<?php  

$array = [1,2,3,[5,6,7]];
$nu_array = null;
$callback = function ( $item ) use(&$callback, &$nu_array) {
    if (!is_array($item)) {
    $nu_array[] = $item;
    }
    else
    if ( is_array( $item ) ) {
     foreach( array_values($item) as $v) {
         if ( !(is_array($v))) {
             $nu_array[] = $v;
         }
         else
         { 
             $callback( $v );
         continue;
         }    
     }
    }
};

array_walk($array, $callback);
print_r($nu_array);

The one drawback of the preceding example is that it involves writing far more code than the following solution which uses array_walk_recursive() along with a simplified callback:

<?php  

$array = [1,2,3,[5,6,7]];

$nu_array = [];
array_walk_recursive($array, function ( $item ) use(&$nu_array )
                     {
                         $nu_array[] = $item;
                     }
);
print_r($nu_array);

See live code

This example seems preferable to the previous one, hiding the details about how values are extracted from a multidimensional array. Surely, iteration occurs, but whether it entails recursion or control structure(s), you'll only know from perusing array.c. Since functional programming focuses on input and output rather than the minutiae of obtaining a result, surely one can remain unconcerned about how behind-the-scenes iteration occurs, that is until a perspective employer poses such a question.

How to set value to form control in Reactive Forms in Angular

Try this.

editqueForm =  this.fb.group({
   user: [this.question.user],
   questioning: [this.question.questioning, Validators.required],
   questionType: [this.question.questionType, Validators.required],
   options: new FormArray([])
})

setValue() and patchValue()

if you want to set the value of one control, this will not work, therefor you have to set the value of both controls:

formgroup.setValue({name: ‘abc’, age: ‘25’});

It is necessary to mention all the controls inside the method. If this is not done, it will throw an error.

On the other hand patchvalue() is a lot easier on that part, let’s say you only want to assign the name as a new value:

formgroup.patchValue({name:’abc’});

Qt 5.1.1: Application failed to start because platform plugin "windows" is missing

For anyone coming from QT version 5.14.0, it took me 2 days to find this piece statment of bug:

windeployqt does not work for MinGW QTBUG-80763 Will be fixed in 5.14.1

https://wiki.qt.io/Qt_5.14.0_Known_Issues

So be aware. Using windeployqt withMinGW will give the same error stated here.

Pausing a batch file for amount of time

ping -n 11 -w 1000 127.0.0.1 > nul

Update

Beginner's mistake. Ping doesn't wait 1000 ms before or after an request, but inbetween requests. So to wait 10 seconds, you'll have to do 11 pings to have 10 'gaps' of a second inbetween.

pandas dataframe groupby datetime month

Slightly alternative solution to @jpp's but outputting a YearMonth string:

df['YearMonth'] = pd.to_datetime(df['Date']).apply(lambda x: '{year}-{month}'.format(year=x.year, month=x.month))

res = df.groupby('YearMonth')['Values'].sum()

What does it mean to have an index to scalar variable error? python

IndexError: invalid index to scalar variable happens when you try to index a numpy scalar such as numpy.int64 or numpy.float64. It is very similar to TypeError: 'int' object has no attribute '__getitem__' when you try to index an int.

>>> a = np.int64(5)
>>> type(a)
<type 'numpy.int64'>
>>> a[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: invalid index to scalar variable.
>>> a = 5
>>> type(a)
<type 'int'>
>>> a[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'

TypeError: cannot perform reduce with flexible type

When your are trying to apply prod on string type of value like:

['-214' '-153' '-58' ..., '36' '191' '-37']

you will get the error.

Solution: Append only integer value like [1,2,3], and you will get your expected output.

If the value is in string format before appending then, in the array you can convert the type into int type and store it in a list.

Is there a good JavaScript minifier?

JavaScript Minifier gives a good API you can use programatically:

curl -X POST -s --data-urlencode 'input=$(function() { alert("Hello, World!"); });' http://javascript-minifier.com/raw

Or by uploading a file and redirecting to a new file:

curl -X POST -s --data-urlencode '[email protected]' http://javascript-minifier.com/raw > ready.min.js

Hope that helps.

jquery how to empty input field

if you hit the "back" button it usually tends to stick, what you can do is when the form is submitted clear the element then before it goes to the next page but after doing with the element what you need to.

    $('#shares').keyup(function(){
                payment = 0;
                calcTotal();
                gtotal = ($('#shares').val() * 1) + payment;
                gtotal = gtotal.toFixed(2);
                $('#shares').val('');
                $("p.total").html("Total Payment: <strong>" + gtotal + "</strong>");
            });

Creating an empty Pandas DataFrame, then filling it?

Initialize empty frame with column names

import pandas as pd

col_names =  ['A', 'B', 'C']
my_df  = pd.DataFrame(columns = col_names)
my_df

Add a new record to a frame

my_df.loc[len(my_df)] = [2, 4, 5]

You also might want to pass a dictionary:

my_dic = {'A':2, 'B':4, 'C':5}
my_df.loc[len(my_df)] = my_dic 

Append another frame to your existing frame

col_names =  ['A', 'B', 'C']
my_df2  = pd.DataFrame(columns = col_names)
my_df = my_df.append(my_df2)

Performance considerations

If you are adding rows inside a loop consider performance issues. For around the first 1000 records "my_df.loc" performance is better, but it gradually becomes slower by increasing the number of records in the loop.

If you plan to do thins inside a big loop (say 10M? records or so), you are better off using a mixture of these two; fill a dataframe with iloc until the size gets around 1000, then append it to the original dataframe, and empty the temp dataframe. This would boost your performance by around 10 times.

Get text of label with jquery

Try using the html() function.

$('#<%=Label1.ClientID%>').html();

You're also missing the # to make it an ID you're searching for. Without the #, it's looking for a tag type.

How to append contents of multiple files into one file

If all your files are in single directory you can simply do

cat * > 0.txt

Files 1.txt,2.txt, .. will go into 0.txt

Razor MVC Populating Javascript array with Model Array

The valid syntax with named fields:

  var array = [];

     @foreach (var item in model.List)
     {
        @:array.push({ 
                       "Project": "@item.Project",
                       "ProjectOrgUnit": "@item.ProjectOrgUnit"
                     });
     }

I can't delete a remote master branch on git

As explained in "Deleting your master branch" by Matthew Brett, you need to change your GitHub repo default branch.

You need to go to the GitHub page for your forked repository, and click on the “Settings” button.

Click on the "Branches" tab on the left hand side. There’s a “Default branch” dropdown list near the top of the screen.

From there, select placeholder (where placeholder is the dummy name for your new default branch).

Confirm that you want to change your default branch.

Now you can do (from the command line):

git push origin :master

Or, since 2012, you can delete that same branch directly on GitHub:

GitHub deletion

That was announced in Sept. 2013, a year after I initially wrote that answer.

For small changes like documentation fixes, typos, or if you’re just a walking software compiler, you can get a lot done in your browser without needing to clone the entire repository to your computer.


Note: for BitBucket, Tum reports in the comments:

About the same for Bitbucket

Repo -> Settings -> Repository details -> Main branch

Take nth column in a text file

If your file contains n lines, then your script has to read the file n times; so if you double the length of the file, you quadruple the amount of work your script does — and almost all of that work is simply thrown away, since all you want to do is loop over the lines in order.

Instead, the best way to loop over the lines of a file is to use a while loop, with the condition-command being the read builtin:

while IFS= read -r line ; do
    # $line is a single line of the file, as a single string
    : ... commands that use $line ...
done < input_file.txt

In your case, since you want to split the line into an array, and the read builtin actually has special support for populating an array variable, which is what you want, you can write:

while read -r -a line ; do
    echo ""${line[1]}" "${line[3]}"" >> out.txt
done < /path/of/my/text

or better yet:

while read -r -a line ; do
    echo "${line[1]} ${line[3]}"
done < /path/of/my/text > out.txt

However, for what you're doing you can just use the cut utility:

cut -d' ' -f2,4 < /path/of/my/text > out.txt

(or awk, as Tom van der Woerdt suggests, or perl, or even sed).

In Python, what happens when you import inside of a function?

Does it re-import every time the function is run?

No; or rather, Python modules are essentially cached every time they are imported, so importing a second (or third, or fourth...) time doesn't actually force them to go through the whole import process again. 1

Does it import once at the beginning whether or not the function is run?

No, it is only imported if and when the function is executed. 2, 3

As for the benefits: it depends, I guess. If you may only run a function very rarely and don't need the module imported anywhere else, it may be beneficial to only import it in that function. Or if there is a name clash or other reason you don't want the module or symbols from the module available everywhere, you may only want to import it in a specific function. (Of course, there's always from my_module import my_function as f for those cases.)

In general practice, it's probably not that beneficial. In fact, most Python style guides encourage programmers to place all imports at the beginning of the module file.

How to add rows dynamically into table layout

You might be better off using a ListView with a CursorAdapter (or SimpleCursorAdapter).

These are built to show rows from a sqlite database and allow refreshing with minimal programming on your part.

Edit - here is a tutorial involving SimpleCursorAdapter and ListView including sample code.

Excel: the Incredible Shrinking and Expanding Controls

I've found a fix that works, and solves the problem for a single user. If you don't want to read my little rant you can skip straight to the solution.

RANT:

I've been experiencing this stupid problem since the dinosaurs. In the meantime, Microsoft have had plenty of resources to release countless major updates to the Office suite and yet this problem goes unaddressed. It's absolutely infuriating. I have no reason whatsoever to upgrade when basic stuff like this doesn't work. Surely someone at MS uses ActiveX controls in Excel right on a high-res display, no?

I didn't experience this issue on my desktop PC, no clue as to why, but on my Surface Pro 4 my ActiveX controls go bananas whenever I click them.

Today I decided to get to the bottom of this. I searched high and low, tried a every solution proposed on various forums (none of which works by the way). It doesn't matter if the controls are grouped or not, locked or not, hotfix installed or not.

Yesterday I had another problem with things misbehaving in another app called Traktor (DJ software), where controls would jump around when display scaling was set to a value that was not an exact multiple of 100%. A user found the solution was to edit the compatibility mode for this application. So I did the same for Excel, and it worked! Now my controls stay put, regardless of display resolution and scaling.

SOLUTION:

(Ensure Excel is not running)

  1. Locate EXCEL.EXE (on my system this can be found at C:\Program Files\Microsoft Office\Office16\EXCEL.EXE)
  2. Rename "EXCEL.EXE" to "_EXCEL.EXE" (basically change it to something else)
  3. Right-click renamed EXCEL.EXE file, then go to Properties > Compatiblity tab > Settings section
  4. Set Override high DPI scaling behaviour = Enabled, and Scaling performed by = Application
  5. Click OK
  6. Rename to "_EXCEL.EXE" back to "EXCEL.EXE"

Now Excel will run at its native resolution and ActiveX controls won't go awry. The only downside is that Excel won't respond to screen scaling, so things may look a little smaller than one would like. On my Surface Pro 4 is more than acceptable

NOTES:

1) Steps 2 and 6 are required with Excel 2016, because the Properties dialog for EXCEL.EXE does not offer the Compatibility tab. After renaming, the tab becomes available.

2) This solution only works on a one-user basis. That is, if you send an Excel file containing ActiveX controls to your colleagues, the ActiveX controls won't display correctly on their system unless they change the compatibility mode settings.

3) After applying this hack, previously corrupted Excel files appear to fix themselves when you open them, with all controls recovering their original intended dimensions.

Please test and comment, I hope this can help someone, cheers!

jQuery - Trigger event when an element is removed from the DOM

I couldn't get this answer to work with unbinding (despite the update see here), but was able to figure out a way around it. The answer was to create a 'destroy_proxy' special event that triggered a 'destroyed' event. You put the event listener on both 'destroyed_proxy' and 'destroyed', then when you want to unbind, you just unbind the 'destroyed' event:

var count = 1;
(function ($) {
    $.event.special.destroyed_proxy = {
        remove: function (o) {
            $(this).trigger('destroyed');
        }
    }
})(jQuery)

$('.remove').on('click', function () {
    $(this).parent().remove();
});

$('li').on('destroyed_proxy destroyed', function () {
    console.log('Element removed');
    if (count > 2) {
        $('li').off('destroyed');
        console.log('unbinded');
    }
    count++;
});

Here is a fiddle

How to set background color of an Activity to white programmatically?

View randview = new View(getBaseContext());
randview = (View)findViewById(R.id.container);
randview.setBackgroundColor(Color.BLUE);

worked for me. thank you.

How to select the Date Picker In Selenium WebDriver

Do not inject javascript. That is a bad practice.

I would model the DatePicker as an element like textbox / select as shown below.

For the detailed answer - check here- http://www.testautomationguru.com/selenium-webdriver-automating-custom-controls-datepicker/

public class DatePicker {

    private static final String dateFormat = "dd MMM yyyy";

    @FindBy(css = "a.ui-datepicker-prev")
    private WebElement prev;

    @FindBy(css = "a.ui-datepicker-next")
    private WebElement next;

    @FindBy(css = "div.ui-datepicker-title")
    private WebElement curDate;

    @FindBy(css = "a.ui-state-default")
    private List < WebElement > dates;

    public void setDate(String date) {

        long diff = this.getDateDifferenceInMonths(date);
        int day = this.getDay(date);

        WebElement arrow = diff >= 0 ? next : prev;
        diff = Math.abs(diff);

        //click the arrows
        for (int i = 0; i < diff; i++)
            arrow.click();

        //select the date
        dates.stream()
            .filter(ele - > Integer.parseInt(ele.getText()) == day)
            .findFirst()
            .ifPresent(ele - > ele.click());

    }

    private int getDay(String date) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(dateFormat);
        LocalDate dpToDate = LocalDate.parse(date, dtf);
        return dpToDate.getDayOfMonth();
    }

    private long getDateDifferenceInMonths(String date) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(dateFormat);
        LocalDate dpCurDate = LocalDate.parse("01 " + this.getCurrentMonthFromDatePicker(), dtf);
        LocalDate dpToDate = LocalDate.parse(date, dtf);
        return YearMonth.from(dpCurDate).until(dpToDate, ChronoUnit.MONTHS);
    }

    private String getCurrentMonthFromDatePicker() {
        return this.curDate.getText();
    }

}

In bootstrap how to add borders to rows without adding up?

Here is one solution:

div.row { 
  border: 1px solid;
  border-bottom: 0px;
}
.container div.row:last-child {
  border-bottom: 1px solid;
}

I'm not 100% its the most effiecent, but it works :D

http://jsfiddle.net/aaronmallen/7cb3Y/2/

Setting the JVM via the command line on Windows

If you have 2 installations of the JVM. Place the version upfront. Linux : export PATH=/usr/lib/jvm/java-8-oracle/bin:$PATH

This eliminates the ambiguity.

Is there a function to make a copy of a PHP array to another?

When you do

$array_x = $array_y;

PHP copies the array, so I'm not sure how you would have gotten burned. For your case,

global $foo;
$foo = $obj->bar;

should work fine.

In order to get burned, I would think you'd either have to have been using references or expecting objects inside the arrays to be cloned.

Contains case insensitive

If referrer is an array, you can use findIndex()

 if(referrer.findIndex(item => 'ral' === item.toLowerCase()) == -1) {...}

When to use static classes in C#

I use static classes as a means to define "extra functionality" that an object of a given type could use under a specific context. Usually they turn out to be utility classes.

Other than that, I think that "Use a static class as a unit of organization for methods not associated with particular objects." describe quite well their intended usage.

Disabling browser caching for all browsers from ASP.NET

I'm going to test adding the no-store tag to our site to see if this makes a difference to browser caching (Chrome has sometimes been caching the pages). I also found this article very useful on documentation on how and why caching works and will look at ETag's next if the no-store is not reliable:

http://www.mnot.net/cache_docs/

http://en.wikipedia.org/wiki/HTTP_ETag

Determine a user's timezone

Here is a more complete way.

  1. Get the timezone offset for the user
  2. Test some days on daylight saving boundaries to determine if they are in a zone that uses daylight saving.

An excerpt is below:

function TimezoneDetect(){
    var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear());
    var intOffset = 10000; //set initial offset high so it is adjusted on the first attempt
    var intMonth;
    var intHoursUtc;
    var intHours;
    var intDaysMultiplyBy;

    // Go through each month to find the lowest offset to account for DST
    for (intMonth=0;intMonth < 12;intMonth++){
        //go to the next month
        dtDate.setUTCMonth(dtDate.getUTCMonth() + 1);

        // To ignore daylight saving time look for the lowest offset.
        // Since, during DST, the clock moves forward, it'll be a bigger number.
        if (intOffset > (dtDate.getTimezoneOffset() * (-1))){
            intOffset = (dtDate.getTimezoneOffset() * (-1));
        }
    }

    return intOffset;
}

Getting TZ and DST from JS (via Way Back Machine)

Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?

I use that construction whenever I don't want to add complexity to the problem. It's just a list, no need to say what kind of List it is, as it doesn't matter to the problem. I often use Collection for most of my solutions, as, in the end, most of the times, for the rest of the software, what really matters is the content it holds, and I don't want to add new objects to the Collection.

Futhermore, you use that construction when you think that you may want to change the implemenation of list you are using. Let's say you were using the construction with an ArrayList, and your problem wasn't thread safe. Now, you want to make it thread safe, and for part of your solution, you change to use a Vector, for example. As for the other uses of that list won't matter if it's a AraryList or a Vector, just a List, no new modifications will be needed.

iOS 7.0 No code signing identities found

I had the exact same problem in development. I solved it by

  1. Go to XCode preferences, view details of the Apple ID, and delete the provisioning file that's complaining.
  2. Go to the Keychain Access, and delete the development certificate that's related to the provisioning file you just deleted.
  3. In Apple Member Center, download the development provisioning file you just deleted locally, double click the file to make sure it's appearing in XCode.
  4. Download the development certificate you just deleted locally, and double click to make sure it appears in the Keychain Access.
  5. It should be good to go now.

Routing with multiple Get methods in ASP.NET Web API

Only one route enough for this

config.Routes.MapHttpRoute("DefaultApiWithAction", "{controller}/{action}");

And need to specify attribute HttpGet or HttpPost in all actions.

[HttpGet]
public IEnumerable<object> TestGet1()
{
    return new string[] { "value1", "value2" };
}

[HttpGet]
public IEnumerable<object> TestGet2()
{
    return new string[] { "value3", "value4" };
}

How to extract the n-th elements from a list of tuples?

Timings for Python 3.6 for extracting the second element from a 2-tuple list.

Also, added numpy array method, which is simpler to read (but arguably simpler than the list comprehension).

from operator import itemgetter
elements = [(1,1) for _ in range(100000)]

%timeit second = [x[1] for x in elements]
%timeit second = list(map(itemgetter(1), elements))
%timeit second = dict(elements).values()
%timeit second = list(zip(*elements))[1]
%timeit second = np.array(elements)[:,1]

and the timings:

list comprehension:  4.73 ms ± 206 µs per loop
list(map):           5.3 ms ± 167 µs per loop
dict:                2.25 ms ± 103 µs per loop
list(zip)            5.2 ms ± 252 µs per loop
numpy array:        28.7 ms ± 1.88 ms per loop

Note that map() and zip() do not return a list anymore, hence the explicit conversion.

Ruby objects and JSON serialization (without Rails)

Check out Oj. There are gotchas when it comes to converting any old object to JSON, but Oj can do it.

require 'oj'

class A
    def initialize a=[1,2,3], b='hello'
        @a = a
        @b = b
    end
end

a = A.new
puts Oj::dump a, :indent => 2

This outputs:

{
  "^o":"A",
  "a":[
    1,
    2,
    3
  ],
 "b":"hello"
}

Note that ^o is used to designate the object's class, and is there to aid deserialization. To omit ^o, use :compat mode:

puts Oj::dump a, :indent => 2, :mode => :compat

Output:

{
  "a":[
    1,
    2,
    3
  ],
  "b":"hello"
}

How to make a round button?

You can use google's FloatingActionButton

XMl:

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@android:drawable/ic_dialog_email" />

Java:

  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FloatingActionButton bold = (FloatingActionButton) findViewById(R.id.fab);
    bold.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        // Do Stuff
        }
    });
}

Gradle:

    compile 'com.android.support:design:23.4.0'

Resizing SVG in html?

Open your .svg file with a text editor (it's just XML), and look for something like this at the top:

<svg ... width="50px" height="50px"...

Erase width and height attributes; the defaults are 100%, so it should stretch to whatever the container allows it.

Java - No enclosing instance of type Foo is accessible

Lets understand it with the following simple example. This happens because this is NON-STATIC INNER CLASS. You should need the instance of outer class.

 public class PQ {

    public static void main(String[] args) {

        // create dog object here
        Dog dog = new PQ().new Dog();
        //OR
        PQ pq = new PQ();
        Dog dog1 = pq.new Dog();
    }

    abstract class Animal {
        abstract void checkup();
    }

    class Dog extends Animal {
        @Override
        void checkup() {
            System.out.println("Dog checkup");

        }
    }

    class Cat extends Animal {
        @Override
        void checkup() {
            System.out.println("Cat Checkup");

        }
    }
}

Returning a value even if no result

MySQL has a function to return a value if the result is null. You can use it on a whole query:

SELECT IFNULL( (SELECT field1 FROM table WHERE id = 123 LIMIT 1) ,'not found');

How to pause a vbscript execution?

Script snip below creates a pause sub that displayes the pause text in a string and waits for the Enter key. z can be anything. Great if multilple user intervention required pauses are needed. I just keep it in my standard script template.

Pause("Press Enter to continue")

Sub Pause(strPause)
     WScript.Echo (strPause)
     z = WScript.StdIn.Read(1)
End Sub

Query for documents where array size is greater than 1

db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } )

you can use $gt and $lt in query.

What do &lt; and &gt; stand for?

&lt = less than <, &gt = greater than >

The thread has exited with code 0 (0x0) with no unhandled exception

Well, an application may have a lot of threads running in parallel. Some are run by you, the coder, some are run by framework classes (espacially if you are in a GUI environnement).

When a thread has finished its task, it exits and stops to exist. There ie nothing alarming in this and you should not care.

SQL Server Service not available in service list after installation of SQL Server Management Studio

downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?

You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.

http://www.microsoft.com/en-us/download/details.aspx?id=1695

Do I need to explicitly call the base virtual destructor?

No, destructors are called automatically in the reverse order of construction. (Base classes last). Do not call base class destructors.

Change the "No file chosen":

Just change the width of the input. Around 90px

<input type="file" style="width: 90px" />

An array of List in c#

use

List<int>[] a = new List<int>[100];

Why does MSBuild look in C:\ for Microsoft.Cpp.Default.props instead of c:\Program Files (x86)\MSBuild? ( error MSB4019)

I was facing the same issue with MSBuild for VS 17

I solved this by applying the following steps:

  • In my case the Microsoft.Cpp.Default.props file was located at C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\Common7\IDE\VC\VCTargets so I created VCTragetsPath string in the registry under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0 with value C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\Common7\IDE\VC\VCTargets

  • I also made my Jenkins run as an admin user

This solved my issue.

How do I make a composite key with SQL Server Management Studio?

create table myTable 
(
    Column1 int not null,
    Column2 int not null
)
GO


ALTER TABLE myTable
    ADD  PRIMARY KEY (Column1,Column2)
GO

Getting the array length of a 2D array in Java

If you have this array:

String [][] example = {{{"Please!", "Thanks"}, {"Hello!", "Hey", "Hi!"}},
                       {{"Why?", "Where?", "When?", "Who?"}, {"Yes!"}}};

You can do this:

example.length;

= 2

example[0].length;

= 2

example[1].length;

= 2

example[0][1].length;

= 3

example[1][0].length;

= 4

Reload chart data via JSON with Highcharts

The other answers didn't work for me. I found the answer in their documentation:

http://api.highcharts.com/highcharts#Series

Using this method (see JSFiddle example):

var chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container'
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]        
    }]
});

// the button action
$('#button').click(function() {
    chart.series[0].setData([129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4] );
});

Redirect all to index.php using htaccess

There is one "trick" for this problem that fits all scenarios, a so obvious solution that you will have to try it to believe it actually works... :)

Here it is...

<IfModule mod_rewrite.c>

   RewriteEngine On

   RewriteCond %{REQUEST_FILENAME}  -f [OR]
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteRule ^(.*)$ index.php [L,QSA]

</IfModule>

Basically, you are asking MOD_REWRITE to forward to index.php the URI request always when a file exists AND always when the requested file doesn't exist!

When investigating the source code of MOD-REWRITE to understand how it works I realized that all its checks always happen after the verification if the referenced file exists or not. Only then the RegEx are processed. Even when your URI points to a folder, Apache will enforce the check for the index files listed in its configuration file.

Based on that simple discovery, turned obvious a simple file validation would be enough for all possible calls, as far as we double-tap the file presence check and route both results to the same end-point, covering 100% of the possibilities.

IMPORTANT: Notice there is no "/" in index.php. By default, MOD_REWRITE will use the folder it is set as "base folder" for the forwarding. The beauty of it is that it doesn't necessarily need to be the "root folder" of the site, allowing this solution work for localhost/ and/or any subfolder you apply it.

Ultimately, some other solutions I tested before (the ones that appeared to be working fine) broke the PHP ability to "require" a file via its relative path, which is a bummer. Be careful.

Some people may say this is an inelegant solution. It may be, actually, but as far as tests, in several scenarios, several servers, several different Apache versions, etc., this solution worked 100% on all cases!

How can I add an ampersand for a value in a ASP.net/C# app config file value

Have you tried this?

<appSettings>  
  <add key="myurl" value="http://www.myurl.com?&amp;cid=&amp;sid="/>
<appSettings>

Accessing UI (Main) Thread safely in WPF

The best way to go about it would be to get a SynchronizationContext from the UI thread and use it. This class abstracts marshalling calls to other threads, and makes testing easier (in contrast to using WPF's Dispatcher directly). For example:

class MyViewModel
{
    private readonly SynchronizationContext _syncContext;

    public MyViewModel()
    {
        // we assume this ctor is called from the UI thread!
        _syncContext = SynchronizationContext.Current;
    }

    // ...

    private void watcher_Changed(object sender, FileSystemEventArgs e)
    {
         _syncContext.Post(o => DGAddRow(crp.Protocol, ft), null);
    }
}

How to copy marked text in notepad++

This is similar to https://superuser.com/questions/477628/export-all-regular-expression-matches-in-textpad-or-notepad-as-a-list.

I hope you are trying to extract :
"Performance"
"Maintenance"
"System Stability"

Here is the way - Step 1/3: Open Search->Find->Replace Tab , select Regular Expression Radio button. Enter in Find what : (\"[a-zA-Z0-9\s]+\") and in Replace with : \n\1 and click Replace All buttton. Before Clicking Replace All

Step 2/3: After first step your keywords will be in next lines.(as shown in next image). Now go to Mark tab and enter the same regex expression in Find what: Field. Put check mark on Bookmark Line. Then Click Mark All. Bookmark the lines

Step 3/3 : Goto Search -> Bookmarks -> Remove unmarked lines.Remove Unmarked lines

So you have the final result as belowFinal Result

How can you run a command in bash over and over until success?

To elaborate on @Marc B's answer,

$ passwd
$ while [ $? -ne 0 ]; do !!; done

Is nice way of doing the same thing that's not command specific.

how to sync windows time from a ntp time server in command

If you just need to resync windows time, open an elevated command prompt and type:

w32tm /resync

C:\WINDOWS\system32>w32tm /resync 
Sending resync command to local computer 
The command completed successfully.

How to call a javaScript Function in jsp on page load without using <body onload="disableView()">

Either use window.onload this way

<script>
    window.onload = function() {
        // ...
    }
</script>

or alternatively

<script>
    window.onload = functionName;
</script>

(yes, without the parentheses)


Or just put the script at the very bottom of page, right before </body>. At that point, all HTML DOM elements are ready to be accessed by document functions.

<body>
    ...

    <script>
        functionName();
    </script>
</body>

Converting byte array to string in javascript

Didn't find any solution that would work with UTF-8 characters. String.fromCharCode is good until you meet 2 byte character.

For example Hüser will come as [0x44,0x61,0x6e,0x69,0x65,0x6c,0x61,0x20,0x48,0xc3,0xbc,0x73,0x65,0x72]

But if you go through it with String.fromCharCode you will have Hüser as each byte will be converted to a char separately.

Solution

Currently I'm using following solution:

function pad(n) { return (n.length < 2 ? '0' + n : n); }
function decodeUtf8(data) {
  return decodeURIComponent(
    data.map(byte => ('%' + pad(byte.toString(16)))).join('')
  );
}

filter items in a python dictionary where keys contain a specific string

Go for whatever is most readable and easily maintainable. Just because you can write it out in a single line doesn't mean that you should. Your existing solution is close to what I would use other than I would user iteritems to skip the value lookup, and I hate nested ifs if I can avoid them:

for key, val in d.iteritems():
    if filter_string not in key:
        continue
    # do something

However if you realllly want something to let you iterate through a filtered dict then I would not do the two step process of building the filtered dict and then iterating through it, but instead use a generator, because what is more pythonic (and awesome) than a generator?

First we create our generator, and good design dictates that we make it abstract enough to be reusable:

# The implementation of my generator may look vaguely familiar, no?
def filter_dict(d, filter_string):
    for key, val in d.iteritems():
        if filter_string not in key:
            continue
        yield key, val

And then we can use the generator to solve your problem nice and cleanly with simple, understandable code:

for key, val in filter_dict(d, some_string):
    # do something

In short: generators are awesome.

Java FileReader encoding issue

Yes, you need to specify the encoding of the file you want to read.

Yes, this means that you have to know the encoding of the file you want to read.

No, there is no general way to guess the encoding of any given "plain text" file.

The one-arguments constructors of FileReader always use the platform default encoding which is generally a bad idea.

Since Java 11 FileReader has also gained constructors that accept an encoding: new FileReader(file, charset) and new FileReader(fileName, charset).

In earlier versions of java, you need to use new InputStreamReader(new FileInputStream(pathToFile), <encoding>).

Linux command to print directory structure in the form of a tree

Is this what you're looking for tree? It should be in most distributions (maybe as an optional install).

~> tree -d /proc/self/
/proc/self/
|-- attr
|-- cwd -> /proc
|-- fd
|   `-- 3 -> /proc/15589/fd
|-- fdinfo
|-- net
|   |-- dev_snmp6
|   |-- netfilter
|   |-- rpc
|   |   |-- auth.rpcsec.context
|   |   |-- auth.rpcsec.init
|   |   |-- auth.unix.gid
|   |   |-- auth.unix.ip
|   |   |-- nfs4.idtoname
|   |   |-- nfs4.nametoid
|   |   |-- nfsd.export
|   |   `-- nfsd.fh
|   `-- stat
|-- root -> /
`-- task
    `-- 15589
        |-- attr
        |-- cwd -> /proc
        |-- fd
        | `-- 3 -> /proc/15589/task/15589/fd
        |-- fdinfo
        `-- root -> /

27 directories

sample taken from maintainer's web page.

You can add the option -L # where # is replaced by a number, to specify the max recursion depth.

Remove -d to display also files.

Remove the complete styling of an HTML button/submit

I think this provides a more thorough approach:

_x000D_
_x000D_
button, input[type="submit"], input[type="reset"] {_x000D_
 background: none;_x000D_
 color: inherit;_x000D_
 border: none;_x000D_
 padding: 0;_x000D_
 font: inherit;_x000D_
 cursor: pointer;_x000D_
 outline: inherit;_x000D_
}
_x000D_
<button>Example</button>
_x000D_
_x000D_
_x000D_

bash assign default value

You can also use := construct to assign and decide on action in one step. Consider following example:

# Example of setting default server and reporting it's status

server=$1
if [[ ${server:=localhost} =~ [a-z] ]]      # 'localhost' assigned here to $server
then    echo "server is localhost"          # echo is triggered since letters were found in $server
else
        echo "server was set" # numbers were passed
fi

If $1 is not empty, localhost will be assigned to server in the if condition field, trigger match and report match result. In this way you can assign on the fly and trigger appropriate action.

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

Test if string is a number in Ruby on Rails

Here's a benchmark for common ways to address this problem. Note which one you should use probably depends on the ratio of false cases expected.

  1. If they are relatively uncommon casting is definitely fastest.
  2. If false cases are common and you are just checking for ints, comparison vs a transformed state is a good option.
  3. If false cases are common and you are checking floats, regexp is probably the way to go

If performance doesn't matter use what you like. :-)

Integer checking details:

# 1.9.3-p448
#
# Calculating -------------------------------------
#                 cast     57485 i/100ms
#            cast fail      5549 i/100ms
#                 to_s     47509 i/100ms
#            to_s fail     50573 i/100ms
#               regexp     45187 i/100ms
#          regexp fail     42566 i/100ms
# -------------------------------------------------
#                 cast  2353703.4 (±4.9%) i/s -   11726940 in   4.998270s
#            cast fail    65590.2 (±4.6%) i/s -     327391 in   5.003511s
#                 to_s  1420892.0 (±6.8%) i/s -    7078841 in   5.011462s
#            to_s fail  1717948.8 (±6.0%) i/s -    8546837 in   4.998672s
#               regexp  1525729.9 (±7.0%) i/s -    7591416 in   5.007105s
#          regexp fail  1154461.1 (±5.5%) i/s -    5788976 in   5.035311s

require 'benchmark/ips'

int = '220000'
bad_int = '22.to.2'

Benchmark.ips do |x|
  x.report('cast') do
    Integer(int) rescue false
  end

  x.report('cast fail') do
    Integer(bad_int) rescue false
  end

  x.report('to_s') do
    int.to_i.to_s == int
  end

  x.report('to_s fail') do
    bad_int.to_i.to_s == bad_int
  end

  x.report('regexp') do
    int =~ /^\d+$/
  end

  x.report('regexp fail') do
    bad_int =~ /^\d+$/
  end
end

Float checking details:

# 1.9.3-p448
#
# Calculating -------------------------------------
#                 cast     47430 i/100ms
#            cast fail      5023 i/100ms
#                 to_s     27435 i/100ms
#            to_s fail     29609 i/100ms
#               regexp     37620 i/100ms
#          regexp fail     32557 i/100ms
# -------------------------------------------------
#                 cast  2283762.5 (±6.8%) i/s -   11383200 in   5.012934s
#            cast fail    63108.8 (±6.7%) i/s -     316449 in   5.038518s
#                 to_s   593069.3 (±8.8%) i/s -    2962980 in   5.042459s
#            to_s fail   857217.1 (±10.0%) i/s -    4263696 in   5.033024s
#               regexp  1383194.8 (±6.7%) i/s -    6884460 in   5.008275s
#          regexp fail   723390.2 (±5.8%) i/s -    3613827 in   5.016494s

require 'benchmark/ips'

float = '12.2312'
bad_float = '22.to.2'

Benchmark.ips do |x|
  x.report('cast') do
    Float(float) rescue false
  end

  x.report('cast fail') do
    Float(bad_float) rescue false
  end

  x.report('to_s') do
    float.to_f.to_s == float
  end

  x.report('to_s fail') do
    bad_float.to_f.to_s == bad_float
  end

  x.report('regexp') do
    float =~ /^[-+]?[0-9]*\.?[0-9]+$/
  end

  x.report('regexp fail') do
    bad_float =~ /^[-+]?[0-9]*\.?[0-9]+$/
  end
end

How to justify navbar-nav in Bootstrap 3

I know this is an old post but I would like share my solution. I spent several hours trying to make a justified navigation menu. You do not really need to modify anything in bootstrap css. Just need to add the correct class in the html.

   <nav class="nav navbar-default navbar-fixed-top">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#collapsable-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#top">Brand Name</a>
        </div>
        <div class="collapse navbar-collapse" id="collapsable-1">
            <ul class="nav nav-justified">
                <li><a href="#about-me">About Me</a></li>
                <li><a href="#skills">Skills</a></li>
                <li><a href="#projects">Projects</a></li>
                <li><a href="#contact-me">Contact Me</a></li>
            </ul>
        </div>
    </nav>

This CSS code will simply remove the navbar-brand class when the screen reaches 768px.

media@(min-width: 768px){
   .navbar-brand{
        display: none;
    }
}

How can I show line numbers in Eclipse?

this will be the appropriate solution for asked question:

String lineNumbers = AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER; EditorsUI.getPreferenceStore().setValue(lineNumbers, true);

How to produce an csv output file from stored procedure in SQL Server

Found a really helpful link for that. Using SQLCMD for this is really easier than solving this with a stored procedure

http://www.excel-sql-server.com/sql-server-export-to-excel-using-bcp-sqlcmd-csv.htm

Bootstrap tab activation with JQuery

<div class="tabbable">
<ul class="nav nav-tabs">
    <li class="active"><a href="#aaa" data-toggle="tab">AAA</a></li>
    <li><a href="#bbb" data-toggle="tab">BBB</a></li>
    <li><a href="#ccc" data-toggle="tab">CCC</a></li>
</ul>
<div class="tab-content" id="tabs">
    <div class="tab-pane fade active in" id="aaa">...Content...</div>
    <div class="tab-pane" id="bbb">...Content...</div>
    <div class="tab-pane" id="ccc">...Content...</div>
</div>
</div>   

Add active class to any li element you want to be active after page load. And also adding active class to content div is needed ,fade in classes are useful for a smooth transition.

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

The Best way is to create a user for your application and assign the permissions that are suitable for that user. Dont use 'NT AUTHORITY\NETWORK SERVICE' as your user it has its own vulnerability and it is a user that has permissions to so many things on the OS level. Stay away from this built in user.

Checking version of angular-cli that's installed?

Execute:

ng v

or

ng --version

tell you the current angular cli version number

enter image description here

REST API Token-based Authentication

In the web a stateful protocol is based on having a temporary token that is exchanged between a browser and a server (via cookie header or URI rewriting) on every request. That token is usually created on the server end, and it is a piece of opaque data that has a certain time-to-live, and it has the sole purpose of identifying a specific web user agent. That is, the token is temporary, and becomes a STATE that the web server has to maintain on behalf of a client user agent during the duration of that conversation. Therefore, the communication using a token in this way is STATEFUL. And if the conversation between client and server is STATEFUL it is not RESTful.

The username/password (sent on the Authorization header) is usually persisted on the database with the intent of identifying a user. Sometimes the user could mean another application; however, the username/password is NEVER intended to identify a specific web client user agent. The conversation between a web agent and server based on using the username/password in the Authorization header (following the HTTP Basic Authorization) is STATELESS because the web server front-end is not creating or maintaining any STATE information whatsoever on behalf of a specific web client user agent. And based on my understanding of REST, the protocol states clearly that the conversation between clients and server should be STATELESS. Therefore, if we want to have a true RESTful service we should use username/password (Refer to RFC mentioned in my previous post) in the Authorization header for every single call, NOT a sension kind of token (e.g. Session tokens created in web servers, OAuth tokens created in authorization servers, and so on).

I understand that several called REST providers are using tokens like OAuth1 or OAuth2 accept-tokens to be be passed as "Authorization: Bearer " in HTTP headers. However, it appears to me that using those tokens for RESTful services would violate the true STATELESS meaning that REST embraces; because those tokens are temporary piece of data created/maintained on the server side to identify a specific web client user agent for the valid duration of a that web client/server conversation. Therefore, any service that is using those OAuth1/2 tokens should not be called REST if we want to stick to the TRUE meaning of a STATELESS protocol.

Rubens

How do I free memory in C?

You have to free() the allocated memory in exact reverse order of how it was allocated using malloc().

Note that You should free the memory only after you are done with your usage of the allocated pointers.

memory allocation for 1D arrays:

    buffer = malloc(num_items*sizeof(double));

memory deallocation for 1D arrays:

    free(buffer);

memory allocation for 2D arrays:

    double **cross_norm=(double**)malloc(150 * sizeof(double *));
    for(i=0; i<150;i++)
    {
        cross_norm[i]=(double*)malloc(num_items*sizeof(double));
    }

memory deallocation for 2D arrays:

    for(i=0; i<150;i++)
    {
        free(cross_norm[i]);
    }

    free(cross_norm);

Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

In my case, this error happened because my HTML had a trailing linebreak.

var myHtml = '<p>\
    This should work.\
    But does not.\
</p>\
';

jQuery('.something').append(myHtml); // this causes the error

To avoid the error, you just need to trim the HTML.

jQuery('.something').append(jQuery.trim(myHtml)); // this works

Volatile Vs Atomic

So what will happen if two threads attack a volatile primitive variable at same time?

Usually each one can increment the value. However sometime, both will update the value at the same time and instead of incrementing by 2 total, both thread increment by 1 and only 1 is added.

Does this mean that whosoever takes lock on it, that will be setting its value first.

There is no lock. That is what synchronized is for.

And in if meantime, some other thread comes up and read old value while first thread was changing its value, then doesn't new thread will read its old value?

Yes,

What is the difference between Atomic and volatile keyword?

AtomicXxxx wraps a volatile so they are basically same, the difference is that it provides higher level operations such as CompareAndSwap which is used to implement increment.

AtomicXxxx also supports lazySet. This is like a volatile set, but doesn't stall the pipeline waiting for the write to complete. It can mean that if you read a value you just write you might see the old value, but you shouldn't be doing that anyway. The difference is that setting a volatile takes about 5 ns, bit lazySet takes about 0.5 ns.

How to create a label inside an <input> element?

If you're using HTML5, you can use the placeholder attribute.

<input type="text" name="user" placeholder="Username">

clear table jquery

<table id="myTable" class="table" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Header 1</th>
            <th>Header 2</th>
            <th>Header 3</th>
        </tr>
    </thead>
    <tbody id="tblBody">

    </tbody>
</table>

And Remove:

$("#tblBody").empty();

Is an HTTPS query string secure?

From a "sniff the network packet" point of view a GET request is safe, as the browser will first establish the secure connection and then send the request containing the GET parameters. But GET url's will be stored in the users browser history / autocomplete, which is not a good place to store e.g. password data in. Of course this only applies if you take the broader "Webservice" definition that might access the service from a browser, if you access it only from your custom application this should not be a problem.

So using post at least for password dialogs should be preferred. Also as pointed out in the link littlegeek posted a GET URL is more likely to be written to your server logs.

jQuery events .load(), .ready(), .unload()

Also, I noticed one more difference between .load and .ready. I am opening a child window and I am performing some work when child window opens. .load is called only first time when I open the window and if I don't close the window then .load will not be called again. however, .ready is called every time irrespective of close the child window or not.

LINQ to SQL - Left Outer Join with multiple join conditions

Can be written using composite join key. Also if there is need to select properties from both left and right sides the LINQ can be written as

var result = context.Periods
    .Where(p => p.companyid == 100)
    .GroupJoin(
        context.Facts,
        p => new {p.id, otherid = 17},
        f => new {id = f.periodid, f.otherid},
        (p, f) => new {p, f})
    .SelectMany(
        pf => pf.f.DefaultIfEmpty(),
        (pf, f) => new MyJoinEntity
        {
            Id = pf.p.id,
            Value = f.value,
            // and so on...
        });

Convert UTF-8 to base64 string

It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==, the following should work:

byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

This will output: YWJjZGVmPT0= which is abcdef== encoded in Base64.

Edit:

To decode a Base64 string, simply use Convert.FromBase64String(). E.g.

string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);

At this point, bytes will be a byte[] (not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:

string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);

This will output the original input string, abcdef== in this case.

How to get the python.exe location programmatically?

sys.executable is not reliable if working in an embedded python environment. My suggestions is to deduce it from

import os
os.__file__

Regex replace uppercase with lowercase letters

Regular expression

Find:\w+

Replace:\L$0

Sublime Text uses the Perl Compatible Regular Expressions (PCRE) engine from the Boost library to power regular expressions in search panels.

\L Converts everything up to lowercase

$0 Capture groups

Apache SSL Configuration Error (SSL Connection Error)

#Make sure that you specify the port for both http and https ie.
NameVirtualHost:80
NameVirtualHost:443
#and 
<VirtualHost *:80>
<VirtualHost *:443>

#mixing * and *:443 does not work it has to be *:80 and *:443

How do I include the string header?

Sources telling you to use apstring.h are materials for the Advanced Placement course in computer science. It describes a string class that you'll use through the course, and some of the exam questions may refer to it and expect you to be moderately familiar with it. Unless you're enrolled in that class or studying to take that exam, ignore those sources.

Sources telling you to use string.h are either not really talking about C++, or are severely outdated. You should probably ignore them, too. That header is for the C functions for manipulating null-terminated arrays of characters, also known as C-style strings.

In C++, you should use the string header. Write #include <string> at the top of your file. When you declare a variable, the type is string, and it's in the std namespace, so its full name is std::string. You can avoid having to write the namespace portion of that name all the time by following the example of lots of introductory texts and saying using namespace std at the top of the C++ source files (but generally not at the top of any header files you might write).

Any reason to prefer getClass() over instanceof when generating .equals()?

Correct me if I am wrong, but getClass() will be useful when you want to make sure your instance is NOT a subclass of the class you are comparing with. If you use instanceof in that situation you can NOT know that because:

class A { }

class B extends A { }

Object oA = new A();
Object oB = new B();

oA instanceof A => true
oA instanceof B => false
oB instanceof A => true // <================ HERE
oB instanceof B => true

oA.getClass().equals(A.class) => true
oA.getClass().equals(B.class) => false
oB.getClass().equals(A.class) => false // <===============HERE
oB.getClass().equals(B.class) => true

Wget output document and headers to STDOUT

This will not work:

wget -q -S -O - google.com 1>wget.txt 2>&1

since redirects are evaluated right to left, this sends html to wget.txt and the header to STDOUT:

wget -q -S -O - google.com 2>&1 1>wget.txt

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

Go to Eclipse folder, locate eclipse.ini file, add following entry (before -vmargs if present):

-vm
C:\Program Files\Java\jdk1.7.0_10\bin\javaw.exe

Save file and execute eclipse.exe.

Using Git with Visual Studio

Git Source Control Provider is new plug-in that integrates Git with Visual Studio.

Where do I mark a lambda expression async?

And for those of you using an anonymous expression:

await Task.Run(async () =>
{
   SQLLiteUtils slu = new SQLiteUtils();
   await slu.DeleteGroupAsync(groupname);
});

how to change color of TextinputLayout's label and edittext underline android

<style name="Widget.Design.TextInputLayout" parent="android:Widget">
    <item name="hintTextAppearance">@style/TextAppearance.Design.Hint</item>
    <item name="errorTextAppearance">@style/TextAppearance.Design.Error</item>
</style>

You can override this style for layout

And also you can change inner EditText-item style too.

What does yield mean in PHP?

yield keyword serves for definition of "generators" in PHP 5.5. Ok, then what is a generator?

From php.net:

Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.

A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal function, except that instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over.

From this place: generators = generators, other functions (just a simple functions) = functions.

So, they are useful when:

  • you need to do things simple (or simple things);

    generator is really much simplier then implementing the Iterator interface. other hand is, ofcource, that generators are less functional. compare them.

  • you need to generate BIG amounts of data - saving memory;

    actually to save memory we can just generate needed data via functions for every loop iteration, and after iteration utilize garbage. so here main points is - clear code and probably performance. see what is better for your needs.

  • you need to generate sequence, which depends on intermediate values;

    this is extending of the previous thought. generators can make things easier in comparison with functions. check Fibonacci example, and try to make sequence without generator. Also generators can work faster is this case, at least because of storing intermediate values in local variables;

  • you need to improve performance.

    they can work faster then functions in some cases (see previous benefit);

Loop through all elements in XML using NodeList

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document dom = db.parse("file.xml");
    Element docEle = dom.getDocumentElement();
    NodeList nl = docEle.getChildNodes();
    int length = nl.getLength();
    for (int i = 0; i < length; i++) {
        if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
            Element el = (Element) nl.item(i);
            if (el.getNodeName().contains("staff")) {
                String name = el.getElementsByTagName("name").item(0).getTextContent();
                String phone = el.getElementsByTagName("phone").item(0).getTextContent();
                String email = el.getElementsByTagName("email").item(0).getTextContent();
                String area = el.getElementsByTagName("area").item(0).getTextContent();
                String city = el.getElementsByTagName("city").item(0).getTextContent();
            }
        }
    }

Iterate over all children and nl.item(i).getNodeType() == Node.ELEMENT_NODE is used to filter text nodes out. If there is nothing else in XML what remains are staff nodes.

For each node under stuff (name, phone, email, area, city)

 el.getElementsByTagName("name").item(0).getTextContent(); 

el.getElementsByTagName("name") will extract the "name" nodes under stuff, .item(0) will get you the first node and .getTextContent() will get the text content inside.

Edit: Since we have jackson I would do this in a different way. Define a pojo for the object:

public class Staff {
    private String name;
    private String phone;
    private String email;
    private String area;
    private String city;
...getters setters
}

Then using jackson:

    JsonNode root = new XmlMapper().readTree(xml.getBytes());
    ObjectMapper mapper = new ObjectMapper();
    root.forEach(node -> consume(node, mapper));



private void consume(JsonNode node, ObjectMapper mapper) {
    try {
        Staff staff = mapper.treeToValue(node, Staff.class);
        //TODO your job with staff
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
}

How to select an option from drop down using Selenium WebDriver C#?

 var select = new SelectElement(elementX);
 select.MoveToElement(elementX).Build().Perform();

  var click = (
       from sel in select
       let value = "College"
       select value
       );

How to Replace dot (.) in a string in Java

Use Apache Commons Lang:

String a= "\\*\\";
str = StringUtils.replace(xpath, ".", a);

or with standalone JDK:

String a = "\\*\\"; // or: String a = "/*/";
String replacement = Matcher.quoteReplacement(a);
String searchString = Pattern.quote(".");
String str = xpath.replaceAll(searchString, replacement);

Google Android USB Driver and ADB

Locate the following file

C:\Users\[your name]\.android\adb_usb.ini

And make the following changes:

# ANDROID 3RD PARTY USB VENDOR ID LIST -- DO NOT EDIT.
# USE 'android update adb' TO GENERATE.
# 1 USB VENDOR ID PER LINE.
0x2207

I added 0x2207 to the file. This number is part of the hardware id, which can be found under the device's hardware information.

Mine was:

USB\VID_2207&PID_0010&MI_01

(I tried executing android update adb, but it did nothing.)

python: restarting a loop

Here is an example using a generator's send() method:

def restartable(seq):
    while True:
        for item in seq:
            restart = yield item
            if restart:
                break
        else:
            raise StopIteration

Example Usage:

x = [1, 2, 3, 4, 5]
total = 0
r = restartable(x)
for item in r:
    if item == 5 and total < 100:
        total += r.send(True) 
    else:
        total += item

difference between width auto and width 100 percent

It's about margins and border. If you use width: auto, then add border, your div won't become bigger than its container. On the other hand, if you use width: 100% and some border, the element's width will be 100% + border or margin. For more info see this.

convert iso date to milliseconds in javascript

Yes, you can do this in a single line

let ms = Date.parse('2019-05-15 07:11:10.673Z');
console.log(ms);//1557904270673

How to get thread id from a thread pool?

If your class inherits from Thread, you can use methods getName and setName to name each thread. Otherwise you could just add a name field to MyTask, and initialize it in your constructor.

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

If you are having problems with Silverlight projects the solution can be fairly simple. According to my experience in many cases debugging symbols are not being loaded due to the new ".xap" files not being deployed to temporary folder (either internal VS Cassini or IIS Express). In this situation full rebuilds or resetting VS settings won't help. The easiest solution is just to delete temporary internet files within your browser. If you are using IE for Silverlight development and testing I would recommend switching on "Delete browsing history on exit" option in order not to have such issues in the future.

resize font to fit in a div (on one line)

My solution, as a jQuery extension based on Robert Koritnik's answer:

$.fn.fitToWidth=function(){
    $(this).wrapInner("<span style='display:inline;font:inherit;white-space:inherit;'></span>").each(function(){
        var $t=$(this);
        var a=$t.outerWidth(),
            $s=$t.children("span"),
            f=parseFloat($t.css("font-size"));
        while($t.children("span").outerWidth() > a) $t.css("font-size",--f);
        $t.html($s.html());
    });
}

This actually creates a temporary span inheriting important properties, and compares the width difference. Granted, the while loop needs to be optimised (reduce by a percentage difference calculated between the two sizes).

Example usage:

$(function(){
    $("h1").fitToWidth();
});

use video as background for div

I believe this is what you're looking for. It automatically scaled the video to fit the container.

DEMO: http://jsfiddle.net/t8qhgxuy/

Video need to have height and width always set to 100% of the parent.

HTML:

<div class="one"> CONTENT OVER VIDEO
    <video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video>
</div>

<div class="two">
    <video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video> CONTENT OVER VIDEO
</div>

CSS:

body {
    overflow: scroll;
    padding:  60px 20px;
}

.one {
    width: 90%;
    height: 30vw;
    overflow: hidden;
    border: 15px solid red;
    margin-bottom: 40px;
    position: relative;
}

.two{
    width: 30%;
    height: 300px;
    overflow: hidden;
    border: 15px solid blue;
    position: relative;
}

.video-background { /* class name used in javascript too */
    width: 100%; /* width needs to be set to 100% */
    height: 100%; /* height needs to be set to 100% */
    position: absolute;
    left: 0;
    top: 0;
    z-index: -1;
}

JS:

function scaleToFill() {
    $('video.video-background').each(function(index, videoTag) {
       var $video = $(videoTag),
           videoRatio = videoTag.videoWidth / videoTag.videoHeight,
           tagRatio = $video.width() / $video.height(),
           val;

       if (videoRatio < tagRatio) {
           val = tagRatio / videoRatio * 1.02; <!-- size increased by 2% because value is not fine enough and sometimes leaves a couple of white pixels at the edges -->
       } else if (tagRatio < videoRatio) {
           val = videoRatio / tagRatio * 1.02;
       }

       $video.css('transform','scale(' + val  + ',' + val + ')');

    });    
}

$(function () {
    scaleToFill();

    $('.video-background').on('loadeddata', scaleToFill);

    $(window).resize(function() {
        scaleToFill();
    });
});

How can I check the size of a file in a Windows batch script?

Important to note is the INT32 limit of Batch: 'Invalid number. Numbers are limited to 32-bits of precision.'

Try the following statements:

IF 2147483647 GTR 2147483646 echo A is greater than B (will be TRUE)
IF 2147483648 GTR 2147483647 echo A is greater than B (will be FALSE!)

Any number greater than the max INT32 value will BREAK THE SCRIPT! Seeing as filesize is measured in bytes, the scripts will support a maximum filesize of about 255.9999997615814 MB !

403 Forbidden vs 401 Unauthorized HTTP responses

TL;DR

  • 401: A refusal that has to do with authentication
  • 403: A refusal that has NOTHING to do with authentication

Practical Examples

If apache requires authentication (via .htaccess), and you hit Cancel, it will respond with a 401 Authorization Required

If nginx finds a file, but has no access rights (user/group) to read/access it, it will respond with 403 Forbidden

RFC (2616 Section 10)

401 Unauthorized (10.4.2)

Meaning 1: Need to authenticate

The request requires user authentication. ...

Meaning 2: Authentication insufficient

... If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. ...

403 Forbidden (10.4.4)

Meaning: Unrelated to authentication

... Authorization will not help ...

More details:

  • The server understood the request, but is refusing to fulfill it.

  • It SHOULD describe the reason for the refusal in the entity

  • The status code 404 (Not Found) can be used instead

    (If the server wants to keep this information from client)

Error message 'Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.'

I had the same issue (but on my local) when I was trying to add Entity Framework migration with Package Manager Console.

The way I solved it was by creating a console application where Main() had the following code:

 var dbConfig = new Configuration();
 var dbMigrator = new DbMigrator(dbConfig);
 dbMigrator.Update();

Make sure the Configuration class is the migration Configuration of your failing project. You will need System.Data.Entity.Migrations to use DbMigrator.

Set a breakpoint in your application, and run it. The exception should be caught by Visual Studio (unless you have that exception type set to not break the debug session), and you should be able to find the info you are looking for.

The missing reference in my case was EFProviderWrapperToolkit.

pull/push from multiple remote locations

Doing this manually is no longer necessary, with modern versions of git! See Malvineous's solution, below.

Reproduced here:

git remote set-url origin --push --add <a remote>
git remote set-url origin --push --add <another remote>

Original answer:

This something I’ve been using for quite a while without bad consequences and suggested by Linus Torvalds on the git mailing list.

araqnid’s solution is the proper one for bringing code into your repository… but when you, like me, have multiple equivalent authoritative upstreams (I keep some of my more critical projects cloned to both a private upstream, GitHub, and Codaset), it can be a pain to push changes to each one, every day.

Long story short, git remote add all of your remotes individually… and then git config -e and add a merged-remote. Assuming you have this repository config:

[remote "GitHub"]
    url = [email protected]:elliottcable/Paws.o.git
    fetch = +refs/heads/*:refs/remotes/GitHub/*
[branch "Master"]
    remote = GitHub
    merge = refs/heads/Master
[remote "Codaset"]
    url = [email protected]:elliottcable/paws-o.git
    fetch = +refs/heads/*:refs/remotes/Codaset/*
[remote "Paws"]
    url = [email protected]:Paws/Paws.o.git
    fetch = +refs/heads/*:refs/remotes/Paws/*

… to create a merged-remote for "Paws" and "Codaset", I can add the following after all of those:

[remote "Origin"]
    url = [email protected]:Paws/Paws.o.git
    url = [email protected]:elliottcable/paws-o.git

Once I’ve done this, when I git push Origin Master, it will push to both Paws/Master and Codaset/Master sequentially, making life a little easier.

Notice: Array to string conversion in

One of reasons why you will get this Notice: Array to string conversion in… is that you are combining group of arrays. Example, sorting out several first and last names.

To echo elements of array properly, you can use the function, implode(separator, array) Example:

implode(' ', $var)

result:

first name[1], last name[1]
first name[2], last name[2]

More examples from W3C.

Static variables in JavaScript

There are other similar answers, but none of them quite appealed to me. Here's what I ended up with:

var nextCounter = (function () {
  var counter = 0;
  return function() {
    var temp = counter;
    counter += 1;
    return temp;
  };
})();

PHP: How to get referrer URL?

$_SERVER['HTTP_REFERER'];

But if you run a file (that contains the above code) by directly hitting the URL in the browser then you get the following error.

Notice: Undefined index: HTTP_REFERER

HTML Tags in Javascript Alert() method

You can add HTML into an alert string, but it will not render as HTML. It will just be displayed as a plain string. Simple answer: no.

Correct way to pass multiple values for same parameter name in GET request

Indeed, there is no defined standard. To support that information, have a look at wikipedia, in the Query String chapter. There is the following comment:

While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field.[3][4]

Furthermore, when you take a look at the RFC 3986, in section 3.4 Query, there is no definition for parameters with multiple values.

Most applications use the first option you have shown: http://server/action?id=a&id=b. To support that information, take a look at this Stackoverflow link, and this MSDN link regarding ASP.NET applications, which use the same standard for parameters with multiple values.

However, since you are developing the APIs, I suggest you to do what is the easiest for you, since the caller of the API will not have much trouble creating the query string.

Associative arrays in Shell scripts

I modified Vadim's solution with the following:

####################################################################
# Bash v3 does not support associative arrays
# and we cannot use ksh since all generic scripts are on bash
# Usage: map_put map_name key value
#
function map_put
{
    alias "${1}$2"="$3"
}

# map_get map_name key
# @return value
#
function map_get {
    if type -p "${1}$2"
        then
            alias "${1}$2" | awk -F "'" '{ print $2; }';
    fi
}

# map_keys map_name 
# @return map keys
#
function map_keys
{
    alias -p | grep $1 | cut -d'=' -f1 | awk -F"$1" '{print $2; }'
}

The change is to map_get in order to prevent it from returning errors if you request a key that doesn't exist, though the side-effect is that it will also silently ignore missing maps, but it suited my use-case better since I just wanted to check for a key in order to skip items in a loop.

Setting HttpContext.Current.Session in a unit test

You can try FakeHttpContext:

using (new FakeHttpContext())
{
   HttpContext.Current.Session["CustomerId"] = "customer1";       
}

Check if Cell value exists in Column, and then get the value of the NEXT Cell

After t.thielemans' answer, I worked that just

=VLOOKUP(A1, B:C, 2, FALSE) 

works fine and does what I wanted, except that it returns #N/A for non-matches; so it is suitable for the case where it is known that the value definitely exists in the look-up column.

Edit (based on t.thielemans' comment):

To avoid #N/A for non-matches, do:

=IFERROR(VLOOKUP(A1, B:C, 2, FALSE), "No Match")

Visual Studio 2017 - Git failed with a fatal error

I tried a lot and finally got it working with some modification from what I read in Git - Can't clone remote repository:

  1. Modify Visual Studio 2017 CE installation ? remove Git for windows (installer ? modify ? single components).

  2. Delete everything from C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git.

  3. Modify Visual Studio 2017 CE installation ? add Git for windows (installer ? modify ? single components)

  4. Install Git on windows (32 or 64 bit version), having Git in system path configured.

Maybe point 2 and 3 are not needed; I didn't try.

Now it works OK on my Gogs.

How to comment and uncomment blocks of code in the Office VBA Editor

There is a built-in Edit toolbar in the VBA editor that has the Comment Block and Uncomment Block buttons by default, and other useful tools.

If you right-click any toolbar or menu (or go to the View menu > Toolbars), you will see a list of available toolbars (above the "Customize..." option). The Standard toolbar is selected by default. Select the Edit toolbar and the new toolbar will appear, with the Comment Block buttons in the middle.

enter image description here

*This is a simpler option to the ones mentioned.

What SOAP client libraries exist for Python, and where is the documentation for them?

As I suggested here I recommend you roll your own. It's actually not that difficult and I suspect that's the reason there aren't better Python SOAP libraries out there.

How do I monitor all incoming http requests?

I would install Microsoft Network Monitor, configure the tool so it would only see HTTP packets (filter the port) and start capturing packets.

You could download it here

Obtain smallest value from array in Javascript?

function tinyFriends() {
    let myFriends = ["Mukit", "Ali", "Umor", "sabbir"]
    let smallestFridend = myFriends[0];
    for (i = 0; i < myFriends.length; i++) {
        if (myFriends[i] < smallestFridend) {
            smallestFridend = myFriends[i];
        }
    }
    return smallestFridend   
}

How do I remove the title bar from my app?

In styles.xml file, change DarkActionBar to NoActionBar

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

How to subtract X days from a date using Java calendar?

Someone recommended Joda Time so - I have been using this CalendarDate class http://calendardate.sourceforge.net

It's a somewhat competing project to Joda Time, but much more basic at only 2 classes. It's very handy and worked great for what I needed since I didn't want to use a package bigger than my project. Unlike the Java counterparts, its smallest unit is the day so it is really a date (not having it down to milliseconds or something). Once you create the date, all you do to subtract is something like myDay.addDays(-5) to go back 5 days. You can use it to find the day of the week and things like that. Another example:

CalendarDate someDay = new CalendarDate(2011, 10, 27);
CalendarDate someLaterDay = today.addDays(77);

And:

//print 4 previous days of the week and today
String dayLabel = "";
CalendarDate today = new CalendarDate(TimeZone.getDefault());
CalendarDateFormat cdf = new CalendarDateFormat("EEE");//day of the week like "Mon"
CalendarDate currDay = today.addDays(-4);
while(!currDay.isAfter(today)) {
    dayLabel = cdf.format(currDay);
    if (currDay.equals(today))
        dayLabel = "Today";//print "Today" instead of the weekday name
    System.out.println(dayLabel);
    currDay = currDay.addDays(1);//go to next day
}

How to filter array in subdocument with MongoDB

Above solution works best if multiple matching sub documents are required. $elemMatch also comes in very use if single matching sub document is required as output

db.test.find({list: {$elemMatch: {a: 1}}}, {'list.$': 1})

Result:

{
  "_id": ObjectId("..."),
  "list": [{a: 1}]
}

Comparing two columns, and returning a specific adjacent cell in Excel

Very similar to this question, and I would suggest the same formula in column D, albeit a few changes to the ranges:

=IFERROR(VLOOKUP(C1, A:B, 2, 0), "")

If you wanted to use match, you'd have to use INDEX as well, like so:

=IFERROR(INDEX(B:B, MATCH(C1, A:A, 0)), "")

but this is really lengthy to me and you need to know how to properly use two functions (or three, if you don't know how IFERROR works)!

Note: =IFERROR() can be a substitute of =IF() and =ISERROR() in some cases :)

Multi-dimensional arrays in Bash

After a lot of trial and error i actually find the best, clearest and easiest multidimensional array on bash is to use a regular var. Yep.

Advantages: You don't have to loop through a big array, you can just echo "$var" and use grep/awk/sed. It's easy and clear and you can have as many columns as you like.

Example:

$ var=$(echo -e 'kris hansen oslo\nthomas jonson peru\nbibi abu johnsonville\njohnny lipp peru')

$ echo "$var"
kris hansen oslo
thomas johnson peru
bibi abu johnsonville
johnny lipp peru

If you want to find everyone in peru

$ echo "$var" | grep peru
thomas johnson peru
johnny lipp peru

Only grep(sed) in the third field

$ echo "$var" | sed -n -E '/(.+) (.+) peru/p'
thomas johnson peru
johnny lipp peru

If you only want x field

$ echo "$var" | awk '{print $2}'
hansen
johnson
abu
johnny

Everyone in peru that's called thomas and just return his lastname

$ echo "$var" |grep peru|grep thomas|awk '{print $2}'
johnson

Any query you can think of... supereasy.

To change an item:

$ var=$(echo "$var"|sed "s/thomas/pete/")

To delete a row that contains "x"

$ var=$(echo "$var"|sed "/thomas/d")

To change another field in the same row based on a value from another item

$ var=$(echo "$var"|sed -E "s/(thomas) (.+) (.+)/\1 test \3/")
$ echo "$var"
kris hansen oslo                                                                                                                                             
thomas test peru                                                                                                                                          
bibi abu johnsonville
johnny lipp peru

Of course looping works too if you want to do that

$ for i in "$var"; do echo "$i"; done
kris hansen oslo
thomas jonson peru
bibi abu johnsonville
johnny lipp peru

The only gotcha iv'e found with this is that you must always quote the var(in the example; both var and i) or things will look like this

$ for i in "$var"; do echo $i; done
kris hansen oslo thomas jonson peru bibi abu johnsonville johnny lipp peru

and someone will undoubtedly say it won't work if you have spaces in your input, however that can be fixed by using another delimeter in your input, eg(using an utf8 char now to emphasize that you can choose something your input won't contain, but you can choose whatever ofc):

$ var=$(echo -e 'field one?field two hello?field three yes moin\nfield 1?field 2?field 3 dsdds aq')

$ for i in "$var"; do echo "$i"; done
field one?field two hello?field three yes moin
field 1?field 2?field 3 dsdds aq

$ echo "$var" | awk -F '?' '{print $3}'
field three yes moin
field 3 dsdds aq

$ var=$(echo "$var"|sed -E "s/(field one)?(.+)?(.+)/\1?test?\3/")
$ echo "$var"
field one?test?field three yes moin
field 1?field 2?field 3 dsdds aq

If you want to store newlines in your input, you could convert the newline to something else before input and convert it back again on output(or don't use bash...). Enjoy!

Android TextView Text not getting wrapped

For my case removing input type did the trick, i was using android:inputType="textPostalAddress" due to that my textview was sticked to one line and was not wrapping, removing this fixed the issue.

Update multiple rows in same query using PostgreSQL

For updating multiple rows in a single query, you can try this

UPDATE table_name
SET 
column_1 = CASE WHEN any_column = value and any_column = value THEN column_1_value end,
column_2 = CASE WHEN any_column = value and any_column = value THEN column_2_value end,
column_3 = CASE WHEN any_column = value and any_column = value THEN column_3_value end,
.
.
.
column_n = CASE WHEN any_column = value and any_column = value THEN column_n_value end

if you don't need additional condition then remove and part of this query

How can I configure my makefile for debug and release builds?

This question has appeared often when searching for a similar problem, so I feel a fully implemented solution is warranted. Especially since I (and I would assume others) have struggled piecing all the various answers together.

Below is a sample Makefile which supports multiple build types in separate directories. The example illustrated shows debug and release builds.

Supports ...

  • separate project directories for specific builds
  • easy selection of a default target build
  • silent prep target to create directories needed for building the project
  • build-specific compiler configuration flags
  • GNU Make's natural method of determining if project requires a rebuild
  • pattern rules rather than the obsolete suffix rules

#
# Compiler flags
#
CC     = gcc
CFLAGS = -Wall -Werror -Wextra

#
# Project files
#
SRCS = file1.c file2.c file3.c file4.c
OBJS = $(SRCS:.c=.o)
EXE  = exefile

#
# Debug build settings
#
DBGDIR = debug
DBGEXE = $(DBGDIR)/$(EXE)
DBGOBJS = $(addprefix $(DBGDIR)/, $(OBJS))
DBGCFLAGS = -g -O0 -DDEBUG

#
# Release build settings
#
RELDIR = release
RELEXE = $(RELDIR)/$(EXE)
RELOBJS = $(addprefix $(RELDIR)/, $(OBJS))
RELCFLAGS = -O3 -DNDEBUG

.PHONY: all clean debug prep release remake

# Default build
all: prep release

#
# Debug rules
#
debug: $(DBGEXE)

$(DBGEXE): $(DBGOBJS)
    $(CC) $(CFLAGS) $(DBGCFLAGS) -o $(DBGEXE) $^

$(DBGDIR)/%.o: %.c
    $(CC) -c $(CFLAGS) $(DBGCFLAGS) -o $@ $<

#
# Release rules
#
release: $(RELEXE)

$(RELEXE): $(RELOBJS)
    $(CC) $(CFLAGS) $(RELCFLAGS) -o $(RELEXE) $^

$(RELDIR)/%.o: %.c
    $(CC) -c $(CFLAGS) $(RELCFLAGS) -o $@ $<

#
# Other rules
#
prep:
    @mkdir -p $(DBGDIR) $(RELDIR)

remake: clean all

clean:
    rm -f $(RELEXE) $(RELOBJS) $(DBGEXE) $(DBGOBJS)