Programs & Examples On #Lookup tables

A look-up table is an array or matrix of data that contains items that can be searched. Lookup tables may be arranged as key-value pairs, where the keys are the data items being searched (looked up) and the values are either the actual data or pointers to where the data are located.

Automatically capture output of last command into a variable using Bash?

I think you might be able to hack out a solution that involves setting your shell to a script containing:

#!/bin/sh
bash | tee /var/log/bash.out.log

Then if you set $PROMPT_COMMAND to output a delimiter, you can write a helper function (maybe called _) that gets you the last chunk of that log, so you can use it like:

% find lots*of*files
...
% echo "$(_)"
... # same output, but doesn't run the command again

GlobalConfiguration.Configure() not present after Web API 2 and .NET 4.5.1 migration

If the issue remain after uninstalling and installing Microsoft.AspNet.WebApi.WebHost then also add followings in web.config for globalconfiguration to work

 <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.2.0.0" />
      </dependentAssembly>

Set an empty DateTime variable

The .addwithvalue needs dbnull. You could do something like this:

DateTime? someDate = null;
//...
if (someDate == null)
    myCommand.Parameters.AddWithValue("@SurgeryDate", DBnull.value);

or use a method extension...

  public static class Extensions
    {
        public static SqlParameter AddWithNullValue(this SqlParameterCollection collection, string parameterName, object value)
        {
            if (value == null)
                return collection.AddWithValue(parameterName, DBNull.Value);
            else
                return collection.AddWithValue(parameterName, value);
        }
    }

How much overhead does SSL impose?

I second @erickson: The pure data-transfer speed penalty is negligible. Modern CPUs reach a crypto/AES throughput of several hundred MBit/s. So unless you are on resource constrained system (mobile phone) TLS/SSL is fast enough for slinging data around.

But keep in mind that encryption makes caching and load balancing much harder. This might result in a huge performance penalty.

But connection setup is really a show stopper for many application. On low bandwidth, high packet loss, high latency connections (mobile device in the countryside) the additional roundtrips required by TLS might render something slow into something unusable.

For example we had to drop the encryption requirement for access to some of our internal web apps - they where next to unusable if used from china.

PHP mySQL - Insert new record into table with auto-increment on primary key

I prefer this syntaxis:

$query = "INSERT INTO myTable SET fname='Fname',lname='Lname',website='Website'";

Check if element is visible in DOM

Use the same code as jQuery does:

jQuery.expr.pseudos.visible = function( elem ) {
    return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};

So, in a function:

function isVisible(e) {
    return !!( e.offsetWidth || e.offsetHeight || e.getClientRects().length );
}

Works like a charm in my Win/IE10, Linux/Firefox.45, Linux/Chrome.52...

Many thanks to jQuery without jQuery!

How to generate an MD5 file hash in JavaScript?

You could use crypto-js.

I would also recommend using SHA256, rather than MD5.

To install crypto-js via NPM:

npm install crypto-js

Alternatively you can use a CDN and reference the JS file.

Then to display a MD5 and SHA256 hash, you can do the following:

<script type="text/javascript">
    var md5Hash = CryptoJS.MD5("Test");
    var sha256Hash = CryptoJS.SHA256("Test1");

    console.log(md5Hash.toString());
    console.log(sha256Hash.toString());
</script>

Working example located here, JSFiddle

There are also other JS functions that will generate an MD5 hash, outlined below.

http://www.myersdaily.org/joseph/javascript/md5-text.html

http://pajhome.org.uk/crypt/md5/md5.html

function md5cycle(x, k) {
var a = x[0], b = x[1], c = x[2], d = x[3];

a = ff(a, b, c, d, k[0], 7, -680876936);
d = ff(d, a, b, c, k[1], 12, -389564586);
c = ff(c, d, a, b, k[2], 17,  606105819);
b = ff(b, c, d, a, k[3], 22, -1044525330);
a = ff(a, b, c, d, k[4], 7, -176418897);
d = ff(d, a, b, c, k[5], 12,  1200080426);
c = ff(c, d, a, b, k[6], 17, -1473231341);
b = ff(b, c, d, a, k[7], 22, -45705983);
a = ff(a, b, c, d, k[8], 7,  1770035416);
d = ff(d, a, b, c, k[9], 12, -1958414417);
c = ff(c, d, a, b, k[10], 17, -42063);
b = ff(b, c, d, a, k[11], 22, -1990404162);
a = ff(a, b, c, d, k[12], 7,  1804603682);
d = ff(d, a, b, c, k[13], 12, -40341101);
c = ff(c, d, a, b, k[14], 17, -1502002290);
b = ff(b, c, d, a, k[15], 22,  1236535329);

a = gg(a, b, c, d, k[1], 5, -165796510);
d = gg(d, a, b, c, k[6], 9, -1069501632);
c = gg(c, d, a, b, k[11], 14,  643717713);
b = gg(b, c, d, a, k[0], 20, -373897302);
a = gg(a, b, c, d, k[5], 5, -701558691);
d = gg(d, a, b, c, k[10], 9,  38016083);
c = gg(c, d, a, b, k[15], 14, -660478335);
b = gg(b, c, d, a, k[4], 20, -405537848);
a = gg(a, b, c, d, k[9], 5,  568446438);
d = gg(d, a, b, c, k[14], 9, -1019803690);
c = gg(c, d, a, b, k[3], 14, -187363961);
b = gg(b, c, d, a, k[8], 20,  1163531501);
a = gg(a, b, c, d, k[13], 5, -1444681467);
d = gg(d, a, b, c, k[2], 9, -51403784);
c = gg(c, d, a, b, k[7], 14,  1735328473);
b = gg(b, c, d, a, k[12], 20, -1926607734);

a = hh(a, b, c, d, k[5], 4, -378558);
d = hh(d, a, b, c, k[8], 11, -2022574463);
c = hh(c, d, a, b, k[11], 16,  1839030562);
b = hh(b, c, d, a, k[14], 23, -35309556);
a = hh(a, b, c, d, k[1], 4, -1530992060);
d = hh(d, a, b, c, k[4], 11,  1272893353);
c = hh(c, d, a, b, k[7], 16, -155497632);
b = hh(b, c, d, a, k[10], 23, -1094730640);
a = hh(a, b, c, d, k[13], 4,  681279174);
d = hh(d, a, b, c, k[0], 11, -358537222);
c = hh(c, d, a, b, k[3], 16, -722521979);
b = hh(b, c, d, a, k[6], 23,  76029189);
a = hh(a, b, c, d, k[9], 4, -640364487);
d = hh(d, a, b, c, k[12], 11, -421815835);
c = hh(c, d, a, b, k[15], 16,  530742520);
b = hh(b, c, d, a, k[2], 23, -995338651);

a = ii(a, b, c, d, k[0], 6, -198630844);
d = ii(d, a, b, c, k[7], 10,  1126891415);
c = ii(c, d, a, b, k[14], 15, -1416354905);
b = ii(b, c, d, a, k[5], 21, -57434055);
a = ii(a, b, c, d, k[12], 6,  1700485571);
d = ii(d, a, b, c, k[3], 10, -1894986606);
c = ii(c, d, a, b, k[10], 15, -1051523);
b = ii(b, c, d, a, k[1], 21, -2054922799);
a = ii(a, b, c, d, k[8], 6,  1873313359);
d = ii(d, a, b, c, k[15], 10, -30611744);
c = ii(c, d, a, b, k[6], 15, -1560198380);
b = ii(b, c, d, a, k[13], 21,  1309151649);
a = ii(a, b, c, d, k[4], 6, -145523070);
d = ii(d, a, b, c, k[11], 10, -1120210379);
c = ii(c, d, a, b, k[2], 15,  718787259);
b = ii(b, c, d, a, k[9], 21, -343485551);

x[0] = add32(a, x[0]);
x[1] = add32(b, x[1]);
x[2] = add32(c, x[2]);
x[3] = add32(d, x[3]);

}

function cmn(q, a, b, x, s, t) {
a = add32(add32(a, q), add32(x, t));
return add32((a << s) | (a >>> (32 - s)), b);
}

function ff(a, b, c, d, x, s, t) {
return cmn((b & c) | ((~b) & d), a, b, x, s, t);
}

function gg(a, b, c, d, x, s, t) {
return cmn((b & d) | (c & (~d)), a, b, x, s, t);
}

function hh(a, b, c, d, x, s, t) {
return cmn(b ^ c ^ d, a, b, x, s, t);
}

function ii(a, b, c, d, x, s, t) {
return cmn(c ^ (b | (~d)), a, b, x, s, t);
}

function md51(s) {
txt = '';
var n = s.length,
state = [1732584193, -271733879, -1732584194, 271733878], i;
for (i=64; i<=s.length; i+=64) {
md5cycle(state, md5blk(s.substring(i-64, i)));
}
s = s.substring(i-64);
var tail = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0];
for (i=0; i<s.length; i++)
tail[i>>2] |= s.charCodeAt(i) << ((i%4) << 3);
tail[i>>2] |= 0x80 << ((i%4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i=0; i<16; i++) tail[i] = 0;
}
tail[14] = n*8;
md5cycle(state, tail);
return state;
}

/* there needs to be support for Unicode here,
 * unless we pretend that we can redefine the MD-5
 * algorithm for multi-byte characters (perhaps
 * by adding every four 16-bit characters and
 * shortening the sum to 32 bits). Otherwise
 * I suggest performing MD-5 as if every character
 * was two bytes--e.g., 0040 0025 = @%--but then
 * how will an ordinary MD-5 sum be matched?
 * There is no way to standardize text to something
 * like UTF-8 before transformation; speed cost is
 * utterly prohibitive. The JavaScript standard
 * itself needs to look at this: it should start
 * providing access to strings as preformed UTF-8
 * 8-bit unsigned value arrays.
 */
function md5blk(s) { /* I figured global was faster.   */
var md5blks = [], i; /* Andy King said do it this way. */
for (i=0; i<64; i+=4) {
md5blks[i>>2] = s.charCodeAt(i)
+ (s.charCodeAt(i+1) << 8)
+ (s.charCodeAt(i+2) << 16)
+ (s.charCodeAt(i+3) << 24);
}
return md5blks;
}

var hex_chr = '0123456789abcdef'.split('');

function rhex(n)
{
var s='', j=0;
for(; j<4; j++)
s += hex_chr[(n >> (j * 8 + 4)) & 0x0F]
+ hex_chr[(n >> (j * 8)) & 0x0F];
return s;
}

function hex(x) {
for (var i=0; i<x.length; i++)
x[i] = rhex(x[i]);
return x.join('');
}

function md5(s) {
return hex(md51(s));
}

/* this function is much faster,
so if possible we use it. Some IEs
are the only ones I know of that
need the idiotic second function,
generated by an if clause.  */

function add32(a, b) {
return (a + b) & 0xFFFFFFFF;
}

if (md5('hello') != '5d41402abc4b2a76b9719d911017c592') {
function add32(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF),
msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
}

Then simply use the MD5 function, as shown below:

alert(md5("Test string"));

Another working JS Fiddle here

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

You can just put r in front of the string with your actual path, which denotes a raw string. For example:

data = open(r"C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener")

Pointer vs. Reference

I really think you will benefit from establishing the following function calling coding guidelines:

  1. As in all other places, always be const-correct.

    • Note: This means, among other things, that only out-values (see item 3) and values passed by value (see item 4) can lack the const specifier.
  2. Only pass a value by pointer if the value 0/NULL is a valid input in the current context.

    • Rationale 1: As a caller, you see that whatever you pass in must be in a usable state.

    • Rationale 2: As called, you know that whatever comes in is in a usable state. Hence, no NULL-check or error handling needs to be done for that value.

    • Rationale 3: Rationales 1 and 2 will be compiler enforced. Always catch errors at compile time if you can.

  3. If a function argument is an out-value, then pass it by reference.

    • Rationale: We don't want to break item 2...
  4. Choose "pass by value" over "pass by const reference" only if the value is a POD (Plain old Datastructure) or small enough (memory-wise) or in other ways cheap enough (time-wise) to copy.

    • Rationale: Avoid unnecessary copies.
    • Note: small enough and cheap enough are not absolute measurables.

What is the difference between Collection and List in Java?

Collection is the main interface of Java Collections hierarchy and List(Sequence) is one of the sub interfaces that defines an ordered collection.

Black transparent overlay on image hover with only CSS?

Here's a good way using :after on the image div, instead of the extra overlay div: http://jsfiddle.net/Zf5am/576/

<div class="image">
    <img src="http://www.newyorker.com/online/blogs/photobooth/NASAEarth-01.jpg" alt="" />
</div>

.image {position:relative; border:1px solid black; width:200px; height:200px;}
.image img {max-width:100%; max-height:100%;}
.image:hover:after {content:""; position:absolute; top:0; left:0; bottom:0; right:0; background-color: rgba(0,0,0,0.3);}

How to merge a specific commit in Git

In my use case we had a similar need for CI CD. We used git flow with develop and master branches. Developers are free to merge their changes directly to develop or via a pull request from a feature branch. However to master we merge only the stable commits from the develop branch in an automated way via Jenkins.

In this case doing cherry-pick is not a good option. However we create a local-branch from the commit-id then merge that local-branch to master and perform mvn clean verify(we use maven). If success then release production version artifact to nexus using maven release plugin with localCheckout=true option and pushChanges=false. Finally when everything is success then push the changes and tag to origin.

A sample code snippet:

Assuming you are on master if done manually. However on jenkins, when you checkout the repo you will be on the default branch(master if configured).

git pull  // Just to pull any changes.
git branch local-<commitd-id> <commit-id>  // Create a branch from the given commit-id
git merge local-<commit-id>  // Merge that local branch to master.
mvn clean verify   // Verify if the code is build able
mvn <any args> release:clean release:prepare release:perform // Release artifacts
git push origin/master  // Push the local changes performed above to origin.
git push origin <tag>  // Push the tag to origin

This will give you a full control with a fearless merge or conflict hell.

Feel free to advise in case there is any better option.

How can I rollback an UPDATE query in SQL server 2005?

You need this tool and you can find the transaction and reverse it.

ApexSQL Log

Get first date of current month in java

First day of month of a date:

public static Date firstDayOfMonth(Date d) {
    
    Calendar calendar = new GregorianCalendar();
    calendar.setTime(d);
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    
    return calendar.getTime();  
}

Laravel: Validation unique on update

an even simpler solution tested with version 5.2

in your model

// validator rules
public static $rules = array(
    ...
    'email_address' => 'email|required|unique:users,id'
);

How to count the number of observations in R like Stata command count

The with function will let you use shorthand column references and sum will count TRUE results from the expression(s).

sum(with(aaa, sex==1 & group1==2))
## [1] 3

sum(with(aaa, sex==1 & group2=="A"))
## [1] 2

As @mnel pointed out, you can also do:

nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3

nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2

The benefit of that is that you can do:

nrow(aaa)
## [1] 6

And, the behaviour matches Stata's count almost exactly (syntax notwithstanding).

Changing factor levels with dplyr mutate

I'm not quite sure I understand your question properly, but if you want to change the factor levels of cyl with mutate() you could do:

df <- mtcars %>% mutate(cyl = factor(cyl, levels = c(4, 6, 8)))

You would get:

#> str(df$cyl)
# Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...

Error: Module not specified (IntelliJ IDEA)

This happened to me when I started to work with a colleque's project.

He was using jdk 12.0.2 .

If you are suspicious jdk difference might be the case (Your IDE complains about SDK, JDK etc.):

  1. Download the appropriate jdk
  2. Move new jdk to the folder of your choice. (I use C:\Program Files\Java)
  3. On Intellij, click to the dropdown on top middle bar. Click Edit Configurations. Change jdk.
  4. File -> Invalidate Caches and Restart.

How can I call a method in Objective-C?

use this,
[self score]; 
instead of @selector(score).

Sql Server string to date conversion

Took me a minute to figure this out so here it is in case it might help someone:

In SQL Server 2012 and better you can use this function:

SELECT DATEFROMPARTS(2013, 8, 19);

Here's how I ended up extracting the parts of the date to put into this function:

select
DATEFROMPARTS(right(cms.projectedInstallDate,4),left(cms.ProjectedInstallDate,2),right( left(cms.ProjectedInstallDate,5),2)) as 'dateFromParts'
from MyTable

'Framework not found' in Xcode

If you use CocoaPods try to run:

pod deintegrate
pod update

How to set time to a date object in java

Can you show code which you use for setting date object? Anyway< you can use this code for intialisation of date:

new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2011-01-01 00:00:00")

Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

dialogue in Intellij 20.3

Steps for adding external jars in IntelliJ IDEA:

  1. Click File from the toolbar
  2. Select Project Structure option (CTRL + SHIFT + ALT + S on Windows/Linux, ? + ; on Mac OS X)
  3. Select Modules at the left panel
  4. Select Dependencies tab
  5. Select + icon
  6. Select 1 JARs or directories option

Getting the location from an IP address

PHP has an extension for that.

From PHP.net:

The GeoIP extension allows you to find the location of an IP address. City, State, Country, Longitude, Latitude, and other information as all, such as ISP and connection type can be obtained with the help of GeoIP.

For example:

$record = geoip_record_by_name($ip);
echo $record['city'];

Using multiple IF statements in a batch file

is there a special guideline that should be followed

There is no "standard" way to do batch files, because the vast majority of their authors and maintainers either don't understand programming concepts, or they think they don't apply to batch files.

But I am a programmer. I'm used to compiling, and I'm used to debuggers. Batch files aren't compiled, and you can't run them through a debugger, so they make me nervous. I suggest you be extra strict on what you write, so you can be very sure it will do what you think it does.

There are some coding standards that say: If you write an if statement, you must use braces, even if you don't have an else clause. This saves you from subtle, hard-to-debug problems, and is unambiguously readable. I see no reason you couldn't apply this reasoning to batch files.

Let's take a look at your code.

IF EXIST somefile.txt IF EXIST someotherfile.txt SET var=somefile.txt,someotherfile.txt

And the IF syntax, from the command, HELP IF:

IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXISTS filename command

...

IF EXIST filename (
  command
) ELSE (
  other command
)

So you are chaining IF's as commands.

If you use the common coding-standard rule I mentioned above, you would always want to use parens. Here is how you would do so for your example code:

IF EXIST "somefile.txt" (
  IF EXIST "someotherfile.txt" (
    SET var="somefile.txt,someotherfile.txt"
  )
)

Make sure you cleanly format, and do some form of indentation. You do it in code, and you should do it in your batch scripts.

Also, you should also get in the habit of always quoting your file names, and getting the quoting right. There is some verbiage under HELP FOR and HELP SET that will help you with removing extra quotes when re-quoting strings.

Edit

From your comments, and re-reading your original question, it seems like you want to build a comma separated list of files that exist. For this case, you could simply use a bunch of if/else statements, but that would result in a bunch of duplicated logic, and would not be at all clean if you had more than two files.

A better way is to write a sub-routine that checks for a single file's existence, and appends to a variable if the file specified exists. Then just call that subroutine for each file you want to check for:

@ECHO OFF
SETLOCAL

REM Todo: Set global script variables here
CALL :MainScript
GOTO :EOF

REM MainScript()
:MainScript
  SETLOCAL

  CALL :AddIfExists "somefile.txt" "%files%" "files"
  CALL :AddIfExists "someotherfile.txt" "%files%" "files"

  ECHO.Files: %files%

  ENDLOCAL
GOTO :EOF

REM AddIfExists(filename, existingFilenames, returnVariableName)
:AddIfExists
  SETLOCAL

  IF EXIST "%~1" (
    SET "result=%~1"
  ) ELSE (
    SET "result="
  )

  (
    REM Cleanup, and return result - concatenate if necessary
    ENDLOCAL

    IF "%~2"=="" (
      SET "%~3=%result%"
    ) ELSE (
      SET "%~3=%~2,%result%"
    )
  )
GOTO :EOF

Angular 2: Passing Data to Routes?

It changes in angular 2.1.0

In something.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BlogComponent } from './blog.component';
import { AddComponent } from './add/add.component';
import { EditComponent } from './edit/edit.component';
import { RouterModule } from '@angular/router';
import { MaterialModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
const routes = [
  {
    path: '',
    component: BlogComponent
  },
  {
    path: 'add',
    component: AddComponent
  },
  {
    path: 'edit/:id',
    component: EditComponent,
    data: {
      type: 'edit'
    }
  }

];
@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes),
    MaterialModule.forRoot(),
    FormsModule
  ],
  declarations: [BlogComponent, EditComponent, AddComponent]
})
export class BlogModule { }

To get the data or params in edit component

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params, Data } from '@angular/router';
@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router

  ) { }
  ngOnInit() {

    this.route.snapshot.params['id'];
    this.route.snapshot.data['type'];

  }
}

How to add browse file button to Windows Form using C#

These links explain it with examples

http://dotnetperls.com/openfiledialog

http://www.geekpedia.com/tutorial67_Using-OpenFileDialog-to-open-files.html

private void button1_Click(object sender, EventArgs e)
{
    int size = -1;
    DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
    if (result == DialogResult.OK) // Test result.
    {
       string file = openFileDialog1.FileName;
       try
       {
          string text = File.ReadAllText(file);
          size = text.Length;
       }
       catch (IOException)
       {
       }
    }
    Console.WriteLine(size); // <-- Shows file size in debugging mode.
    Console.WriteLine(result); // <-- For debugging use.
}

HTML CSS Invisible Button

Use CSS background:transparent; to your button/div.

JSFiddle

Process to convert simple Python script into Windows executable

PyInstaller will create a single-file executable if you use the --onefile option (though what it actually does is extracts then runs itself).

There's a simple PyInstaller tutorial here. If you have any questions about using it, please post them...

How to add 10 days to current time in Rails

Some other options, just for reference

-10.days.ago
# Available in Rails 4
DateTime.now.days_ago(-10)

Just list out all options I know:

[1] Time.now + 10.days
[2] 10.days.from_now
[3] -10.days.ago
[4] DateTime.now.days_ago(-10)
[5] Date.today + 10

So now, what is the difference between them if we care about the timezone:

  • [1, 4] With system timezone
  • [2, 3] With config timezone of your Rails app
  • [5] Date only no time included in result

Convert array to JSON

I decided to use the json2 library and I got an error about “cyclic data structures”.

I got it solved by telling json2 how to convert my complex object. Not only it works now but also I have included only the fields I need. Here is how I did it:

OBJ.prototype.toJSON = function (key) {
       var returnObj = new Object();
       returnObj.devid = this.devid;
       returnObj.name = this.name;
       returnObj.speed = this.speed;
       returnObj.status = this.status;
       return returnObj;
   }

Remove HTML Tags in Javascript with Regex

<html>
<head>
<script type="text/javascript">
function striptag(){
var html = /(<([^>]+)>)/gi;
for (i=0; i < arguments.length; i++)
arguments[i].value=arguments[i].value.replace(html, "")
}
</script>
</head> 
<body>
       <form name="myform">
<textarea class="comment" title="comment" name=comment rows=4 cols=40></textarea><br>
<input type="button" value="Remove HTML Tags" onClick="striptag(this.form.comment)">
</form>
</body>
</html>

unix sort descending order

The presence of the n option attached to the -k5 causes the global -r option to be ignored for that field. You have to specify both n and r at the same level (globally or locally).

sort -t $'\t' -k5,5rn

or

sort -rn -t $'\t' -k5,5

eclipse won't start - no java virtual machine was found

you can also copy your JRE folder to eclipse directory and it will work corectly

How to remove unwanted space between rows and columns in table?

_x000D_
_x000D_
table{_x000D_
  border: 1px solid black;_x000D_
}_x000D_
table td {_x000D_
  border: 1px solid black; /* Style just to show the table cell boundaries */_x000D_
}_x000D_
_x000D_
_x000D_
table.no-spacing {_x000D_
  border-spacing:0; /* Removes the cell spacing via CSS */_x000D_
  border-collapse: collapse;  /* Optional - if you don't want to have double border where cells touch */_x000D_
}
_x000D_
<p>Default table:</p>_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>First cell</td>_x000D_
    <td>Second cell</td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
<p>Removed spacing:</p>_x000D_
_x000D_
<table class="no-spacing" cellspacing="0"> <!-- cellspacing 0 to support IE6 and IE7 -->_x000D_
  <tr>_x000D_
    <td>First cell</td>_x000D_
    <td>Second cell</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to make an Android device vibrate? with different frequency?

Update 2017 vibrate(interval) method is deprecated with Android-O(API 8.0)

To support all Android versions use this method.

// Vibrate for 150 milliseconds
private void shakeItBaby() {
    if (Build.VERSION.SDK_INT >= 26) {
        ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE));
    } else {
        ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(150);
    }
}

Kotlin:

// Vibrate for 150 milliseconds
private fun shakeItBaby(context: Context) {
    if (Build.VERSION.SDK_INT >= 26) {
        (context.getSystemService(VIBRATOR_SERVICE) as Vibrator).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE))
    } else {
        (context.getSystemService(VIBRATOR_SERVICE) as Vibrator).vibrate(150)
    }
}

Differences between unique_ptr and shared_ptr

unique_ptr
is a smart pointer which owns an object exclusively.

shared_ptr
is a smart pointer for shared ownership. It is both copyable and movable. Multiple smart pointer instances can own the same resource. As soon as the last smart pointer owning the resource goes out of scope, the resource will be freed.

passing 2 $index values within nested ng-repeat

Just to help someone who get here... You should not use $parent.$index as it's not really safe. If you add an ng-if inside the loop, you get the $index messed!

Right way

  <table>
    <tr ng-repeat="row in rows track by $index" ng-init="rowIndex = $index">
        <td ng-repeat="column in columns track by $index" ng-init="columnIndex = $index">

          <b ng-if="rowIndex == columnIndex">[{{rowIndex}} - {{columnIndex}}]</b>
          <small ng-if="rowIndex != columnIndex">[{{rowIndex}} - {{columnIndex}}]</small>

        </td>
    </tr>
  </table>

Check: plnkr.co/52oIhLfeXXI9ZAynTuAJ

Usage of __slots__?

Each python object has a __dict__ atttribute which is a dictionary containing all other attributes. e.g. when you type self.attr python is actually doing self.__dict__['attr']. As you can imagine using a dictionary to store attribute takes some extra space & time for accessing it.

However, when you use __slots__, any object created for that class won't have a __dict__ attribute. Instead, all attribute access is done directly via pointers.

So if want a C style structure rather than a full fledged class you can use __slots__ for compacting size of the objects & reducing attribute access time. A good example is a Point class containing attributes x & y. If you are going to have a lot of points, you can try using __slots__ in order to conserve some memory.

No Multiline Lambda in Python: Why not?

I'm guilty of practicing this dirty hack in some of my projects which is bit simpler:

    lambda args...:( expr1, expr2, expr3, ...,
            exprN, returnExpr)[-1]

I hope you can find a way to stay pythonic but if you have to do it this less painful than using exec and manipulating globals.

Entity Framework 6 Code first Default value

In .NET Core 3.1 you can do the following in the model class:

    public bool? Active { get; set; } 

In the DbContext OnModelCreating you add the default value.

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Foundation>()
            .Property(b => b.Active)
            .HasDefaultValueSql("1");

        base.OnModelCreating(modelBuilder);
    }

Resulting in the following in the database

enter image description here

Note: If you don't have nullable (bool?) for you property you will get the following warning

The 'bool' property 'Active' on entity type 'Foundation' is configured with a database-generated default. This default will always be used for inserts when the property has the value 'false', since this is the CLR default for the 'bool' type. Consider using the nullable 'bool?' type instead so that the default will only be used for inserts when the property value is 'null'.

What are the safe characters for making URLs?

You are best keeping only some characters (whitelist) instead of removing certain characters (blacklist).

You can technically allow any character, just as long as you properly encode it. But, to answer in the spirit of the question, you should only allow these characters:

  1. Lower case letters (convert upper case to lower)
  2. Numbers, 0 through 9
  3. A dash - or underscore _
  4. Tilde ~

Everything else has a potentially special meaning. For example, you may think you can use +, but it can be replaced with a space. & is dangerous, too, especially if using some rewrite rules.

As with the other comments, check out the standards and specifications for complete details.

Performing Inserts and Updates with Dapper

Instead of using any 3rd party library for query operations, I would rather suggest writing queries on your own. Because using any other 3rd party packages would take away the main advantage of using dapper i.e. flexibility to write queries.

Now, there is a problem with writing Insert or Update query for the entire object. For this, one can simply create helpers like below:

InsertQueryBuilder:

 public static string InsertQueryBuilder(IEnumerable < string > fields) {


  StringBuilder columns = new StringBuilder();
  StringBuilder values = new StringBuilder();


  foreach(string columnName in fields) {
   columns.Append($ "{columnName}, ");
   values.Append($ "@{columnName}, ");

  }
  string insertQuery = $ "({ columns.ToString().TrimEnd(',', ' ')}) VALUES ({ values.ToString().TrimEnd(',', ' ')}) ";

  return insertQuery;
 }

Now, by simply passing the name of the columns to insert, the whole query will be created automatically, like below:

List < string > columns = new List < string > {
 "UserName",
 "City"
}
//QueryBuilder is the class having the InsertQueryBuilder()
string insertQueryValues = QueryBuilderUtil.InsertQueryBuilder(columns);

string insertQuery = $ "INSERT INTO UserDetails {insertQueryValues} RETURNING UserId";

Guid insertedId = await _connection.ExecuteScalarAsync < Guid > (insertQuery, userObj);

You can also modify the function to return the entire INSERT statement by passing the TableName parameter.

Make sure that the Class property names match with the field names in the database. Then only you can pass the entire obj (like userObj in our case) and values will be mapped automatically.

In the same way, you can have the helper function for UPDATE query as well:

  public static string UpdateQueryBuilder(List < string > fields) {
   StringBuilder updateQueryBuilder = new StringBuilder();

   foreach(string columnName in fields) {
    updateQueryBuilder.AppendFormat("{0}=@{0}, ", columnName);
   }
   return updateQueryBuilder.ToString().TrimEnd(',', ' ');
  }

And use it like:

List < string > columns = new List < string > {
 "UserName",
 "City"
}
//QueryBuilder is the class having the UpdateQueryBuilder()
string updateQueryValues = QueryBuilderUtil.UpdateQueryBuilder(columns);

string updateQuery =  $"UPDATE UserDetails SET {updateQueryValues} WHERE UserId=@UserId";

await _connection.ExecuteAsync(updateQuery, userObj);

Though in these helper functions also, you need to pass the name of the fields you want to insert or update but at least you have full control over the query and can also include different WHERE clauses as and when required.

Through this helper functions, you will save the following lines of code:

For Insert Query:

 $ "INSERT INTO UserDetails (UserName,City) VALUES (@UserName,@City) RETURNING UserId";

For Update Query:

$"UPDATE UserDetails SET UserName=@UserName, City=@City WHERE UserId=@UserId";

There seems to be a difference of few lines of code, but when it comes to performing insert or update operation with a table having more than 10 fields, one can feel the difference.

You can use the nameof operator to pass the field name in the function to avoid typos

Instead of:

List < string > columns = new List < string > {
 "UserName",
 "City"
}

You can write:

List < string > columns = new List < string > {
nameof(UserEntity.UserName),
nameof(UserEntity.City),
}

how to convert a string to date in mysql?

The following illustrates the syntax of the STR_TO_DATE() function:

STR_TO_DATE(str,fmt);

The STR_TO_DATE() converts the str string into a date value based on the fmt format string. The STR_TO_DATE() function may return a DATE , TIME, or DATETIME value based on the input and format strings. If the input string is illegal, the STR_TO_DATE() function returns NULL.

The following statement converts a string into a DATE value.

SELECT STR_TO_DATE('21,5,2013','%d,%m,%Y');

enter image description here

Based on the format string ‘%d, %m, %Y’, the STR_TO_DATE() function scans the ‘21,5,2013’ input string.

  • First, it attempts to find a match for the %d format specifier, which is a day of the month (01…31), in the input string. Because the number 21 matches with the %d specifier, the function takes 21 as the day value.
  • Second, because the comma (,) literal character in the format string matches with the comma in the input string, the function continues to check the second format specifier %m , which is a month (01…12), and finds that the number 5 matches with the %m format specifier. It takes the number 5 as the month value.
  • Third, after matching the second comma (,), the STR_TO_DATE() function keeps finding a match for the third format specifier %Y , which is four-digit year e.g., 2012,2013, etc., and it takes the number 2013 as the year value.

The STR_TO_DATE() function ignores extra characters at the end of the input string when it parses the input string based on the format string. See the following example:

SELECT STR_TO_DATE('21,5,2013 extra characters','%d,%m,%Y');

enter image description here

More Details : Reference

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

You can try changing the flag's value

np.load(training_image_names_array,allow_pickle=True)

comparing strings in vb

In vb.net you can actually compare strings with =. Even though String is a reference type, in vb.net = on String has been redefined to do a case-sensitive comparison of contents of the two strings.

You can test this with the following code. Note that I have taken one of the values from user input to ensure that the compiler cannot use the same reference for the two variables like the Java compiler would if variables were defined from the same string Literal. Run the program, type "This" and press <Enter>.

Sub Main()
    Dim a As String = New String("This")
    Dim b As String

    b = Console.ReadLine()

    If a = b Then
        Console.WriteLine("They are equal")
    Else
        Console.WriteLine("Not equal")
    End If
    Console.ReadLine()
End Sub

How to force JS to do math instead of putting two strings together

I'm adding this answer because I don't see it here.

One way is to put a '+' character in front of the value

example:

var x = +'11.5' + +'3.5'

x === 15

I have found this to be the simplest way

In this case, the line:

dots = document.getElementById("txt").value;

could be changed to

dots = +(document.getElementById("txt").value);

to force it to a number

NOTE:

+'' === 0
+[] === 0
+[5] === 5
+['5'] === 5

How to list the size of each file and directory and sort by descending size in Bash?

Apparently --max-depth option is not in Mac OS X's version of the du command. You can use the following instead.

du -h -d 1 | sort -n

Transparent color of Bootstrap-3 Navbar

you can use this for your css , mainly use css3 rgba as your background in order to control the opacity and use a background fallback for older browser , either using a solid color or a transparent .png image.

.navbar {
   background:rgba(0,0,0,0.5);   /* for latest browsers */
   background: #000;  /* fallback for older browsers */
}

More info: http://css-tricks.com/rgba-browser-support/

Using .NET, how can you find the mime type of a file based on the file signature not the extension

This answer is a copy of the author's answer (Richard Gourlay), but improved to solve issues on IIS 8 / win2012 (where function would cause app pool to crash), based on Rohland's comment pointing to http://www.pinvoke.net/default.aspx/urlmon.findmimefromdata

using System.Runtime.InteropServices;

...

public static string GetMimeFromFile(string filename)
{

    if (!File.Exists(filename))
        throw new FileNotFoundException(filename + " not found");

    const int maxContent = 256;

    var buffer = new byte[maxContent];
    using (var fs = new FileStream(filename, FileMode.Open))
    {
        if (fs.Length >= maxContent)
            fs.Read(buffer, 0, maxContent);
        else
            fs.Read(buffer, 0, (int) fs.Length);
    }

    var mimeTypePtr = IntPtr.Zero;
    try
    {
        var result = FindMimeFromData(IntPtr.Zero, null, buffer, maxContent, null, 0, out mimeTypePtr, 0);
        if (result != 0)
        {
            Marshal.FreeCoTaskMem(mimeTypePtr);
            throw Marshal.GetExceptionForHR(result);
        }

        var mime = Marshal.PtrToStringUni(mimeTypePtr);
        Marshal.FreeCoTaskMem(mimeTypePtr);
        return mime;
    }
    catch (Exception e)
    {
        if (mimeTypePtr != IntPtr.Zero)
        {
            Marshal.FreeCoTaskMem(mimeTypePtr);
        }
        return "unknown/unknown";
    }
}

[DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]
private static extern int FindMimeFromData(IntPtr pBC,
    [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,
    [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, SizeParamIndex = 3)] byte[] pBuffer,
    int cbSize,
    [MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed,
    int dwMimeFlags,
    out IntPtr ppwzMimeOut,
    int dwReserved);

In Angular, how do you determine the active route?

Small improvement to @alex-correia-santos answer based on https://github.com/angular/angular/pull/6407#issuecomment-190179875

import {Router, RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
// ...
export class App {
  constructor(private router: Router) {
  }

  // ...

  isActive(instruction: any[]): boolean {
    return this.router.isRouteActive(this.router.generate(instruction));
  }
} 

And use it like this:

<ul class="nav navbar-nav">
    <li [class.active]="isActive(['Home'])">
        <a [routerLink]="['Home']">Home</a>
    </li>
    <li [class.active]="isActive(['About'])">
        <a [routerLink]="['About']">About</a>
    </li>
</ul>

Call an activity method from a fragment

((YourActivityName)getActivity()).functionName();

Example : ((SessionActivity)getActivity()).changeFragment();

Note : class name should be in public

How to put img inline with text

Please make use of the code below to display images inline:

<img style='vertical-align:middle;' src='somefolder/icon.gif'>
<div style='vertical-align:middle; display:inline;'>
Your text here
</div>

Adding a new entry to the PATH variable in ZSH

Here, add this line to .zshrc:

export PATH=/home/david/pear/bin:$PATH

EDIT: This does work, but ony's answer below is better, as it takes advantage of the structured interface ZSH provides for variables like $PATH. This approach is standard for bash, but as far as I know, there is no reason to use it when ZSH provides better alternatives.

Get folder name from full file path

I think you want to get parent folder name from file path. It is easy to get. One way is to create a FileInfo type object and use its Directory property.

Example:

FileInfo fInfo = new FileInfo("c:\projects\roott\wsdlproj\devlop\beta2\text\abc.txt");

String dirName = fInfo.Directory.Name;

Can I get all methods of a class?

public static Method[] getAccessibleMethods(Class clazz) {
    List<Method> result = new ArrayList<Method>();
    while (clazz != null) {
        for (Method method : clazz.getDeclaredMethods()) {
            int modifiers = method.getModifiers();
            if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) {
                result.add(method);
            }
        }
        clazz = clazz.getSuperclass();
    }
    return result.toArray(new Method[result.size()]);
}

What is a void pointer in C++?

A void* can point to anything (it's a raw pointer without any type info).

Strange Jackson exception being thrown when serializing Hibernate object

I tried @JsonDetect and

@JsonIgnoreProperties(value = { "handler", "hibernateLazyInitializer" })

Neither of them worked for me. Using a third-party module seemed like a lot of work to me. So I just tried making a get call on any property of the lazy object before passing to jackson for serlization. The working code snippet looked something like this :

@RequestMapping(value = "/authenticate", produces = "application/json; charset=utf-8")
    @ResponseBody
    @Transactional
    public Account authenticate(Principal principal) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) principal;
        LoggedInUserDetails loggedInUserDetails = (LoggedInUserDetails) usernamePasswordAuthenticationToken.getPrincipal();
        User user = userRepository.findOne(loggedInUserDetails.getUserId());
        Account account = user.getAccount();
        account.getFullName();      //Since, account is lazy giving it directly to jackson for serlization didn't worked & hence, this quick-fix.
        return account;
    }

jQuery .each() with input elements

$.each($('input[type=number]'),function(){
  alert($(this).val());
});

This will alert the value of input type number fields

Demo is present at http://jsfiddle.net/2dJAN/33/

How to provide a mysql database connection in single file in nodejs

I took a similar approach as Sean3z but instead I have the connection closed everytime i make a query.

His way works if it's only executed on the entry point of your app, but let's say you have controllers that you want to do a var db = require('./db'). You can't because otherwise everytime you access that controller you will be creating a new connection.

To avoid that, i think it's safer, in my opinion, to open and close the connection everytime.

here is a snippet of my code.

mysq_query.js

// Dependencies
var mysql   = require('mysql'),
    config  = require("../config");

/*
 * @sqlConnection
 * Creates the connection, makes the query and close it to avoid concurrency conflicts.
 */
var sqlConnection = function sqlConnection(sql, values, next) {

    // It means that the values hasnt been passed
    if (arguments.length === 2) {
        next = values;
        values = null;
    }

    var connection = mysql.createConnection(config.db);
    connection.connect(function(err) {
        if (err !== null) {
            console.log("[MYSQL] Error connecting to mysql:" + err+'\n');
        }
    });

    connection.query(sql, values, function(err) {

        connection.end(); // close the connection

        if (err) {
            throw err;
        }

        // Execute the callback
        next.apply(this, arguments);
    });
}

module.exports = sqlConnection;

Than you can use it anywhere just doing like

var mysql_query = require('path/to/your/mysql_query');
mysql_query('SELECT * from your_table where ?', {id: '1'}, function(err, rows)   {
    console.log(rows);
});

UPDATED: config.json looks like

{
        "db": {
        "user"     : "USERNAME",
        "password" : "PASSWORD",
        "database" : "DATABASE_NAME",
        "socketPath": "/tmp/mysql.sock"
    }
}

Hope this helps.

Do HttpClient and HttpClientHandler have to be disposed between requests?

Dispose() calls the code below, which closes the connections opened by the HttpClient instance. The code was created by decompiling with dotPeek.

HttpClientHandler.cs - Dispose

ServicePointManager.CloseConnectionGroups(this.connectionGroupName);

If you don't call dispose then ServicePointManager.MaxServicePointIdleTime, which runs by a timer, will close the http connections. The default is 100 seconds.

ServicePointManager.cs

internal static readonly TimerThread.Callback s_IdleServicePointTimeoutDelegate = new TimerThread.Callback(ServicePointManager.IdleServicePointTimeoutCallback);
private static volatile TimerThread.Queue s_ServicePointIdlingQueue = TimerThread.GetOrCreateQueue(100000);

private static void IdleServicePointTimeoutCallback(TimerThread.Timer timer, int timeNoticed, object context)
{
  ServicePoint servicePoint = (ServicePoint) context;
  if (Logging.On)
    Logging.PrintInfo(Logging.Web, SR.GetString("net_log_closed_idle", (object) "ServicePoint", (object) servicePoint.GetHashCode()));
  lock (ServicePointManager.s_ServicePointTable)
    ServicePointManager.s_ServicePointTable.Remove((object) servicePoint.LookupString);
  servicePoint.ReleaseAllConnectionGroups();
}

If you haven't set the idle time to infinite then it appears safe not to call dispose and let the idle connection timer kick-in and close the connections for you, although it would be better for you to call dispose in a using statement if you know you are done with an HttpClient instance and free up the resources faster.

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

How do I check if an HTML element is empty using jQuery?

Here's a jQuery filter based on https://stackoverflow.com/a/6813294/698289

$.extend($.expr[':'], {
  trimmedEmpty: function(el) {
    return !$.trim($(el).html());
  }
});

Change a Django form field to a hidden field

Firstly, if you don't want the user to modify the data, then it seems cleaner to simply exclude the field. Including it as a hidden field just adds more data to send over the wire and invites a malicious user to modify it when you don't want them to. If you do have a good reason to include the field but hide it, you can pass a keyword arg to the modelform's constructor. Something like this perhaps:

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
    def __init__(self, *args, **kwargs):
        from django.forms.widgets import HiddenInput
        hide_condition = kwargs.pop('hide_condition',None)
        super(MyModelForm, self).__init__(*args, **kwargs)
        if hide_condition:
            self.fields['fieldname'].widget = HiddenInput()
            # or alternately:  del self.fields['fieldname']  to remove it from the form altogether.

Then in your view:

form = MyModelForm(hide_condition=True)

I prefer this approach to modifying the modelform's internals in the view, but it's a matter of taste.

Can I write or modify data on an RFID tag?

RFID Standards:


  • 125 Khz (low-frequency) tags are write-once/read-many, and usually only contain a small (permanent) unique identification number.

  • 13.56 Mhz (high-frequency) tags are usually read/write, they can typically store about 1 to 2 kilbytes of data in addition to their preset (permanent) unique ID number.

  • 860-960 Mhz (ultra-high-frequency) tags are typically read/write and can have much larger information storage capacity (I think that 64 KB is the highest currently available for passive tags) in addition to their preset (permanent) unique ID number.

More Information


Most read/write tags can be locked to prevent further writing to specific data-blocks in the tag's internal memory, while leaving other blocks unlocked. Different tag manufacturers make their tags differently, though.

Depending on your intended application, you might have to program your own microcontroller to interface with an embedded RFID read/write module using a manufacturer-specific protocol. That's certainly a lot cheaper than buying a complete RFID read/write unit, as they can cost several thousand dollars. With a custom solution, you can build you own unit that does specifically what you want for as little as $200.

Links


RFID Journal

RFID Toys (Book) Website

SkyTek - RFID reader manufacturing company (you can buy their products through third-party retailers & wholesalers like Mouser)

Trossen Robotics - You can buy RFID tags and readers (125 Khz & 13.56 Mhz) from here, among other things

How to center a View inside of an Android Layout?

I was able to center a view using

android:layout_centerHorizontal="true" 

and

android:layout_centerVertical="true" 

params.

What's the effect of adding 'return false' to a click event listener?

using return false in an onclick event stops the browser from processing the rest of the execution stack, which includes following the link in the href attribute.

In other words, adding return false stops the href from working. In your example, this is exactly what you want.

In buttons, it's not necessary because onclick is all it will ever execute -- there is no href to process and go to.

Delete a row from a SQL Server table

Try with paramter

.....................
.....................

    using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = " + @IDNumber, con))
             {
                   command.Paramter.Add("@IDNumber",IDNumber)
                   command.ExecuteNonQuery();
             }

.....................
.....................

No need to close connection in using statement

Function to calculate R2 (R-squared) in R

Why not this:

rsq <- function(x, y) summary(lm(y~x))$r.squared
rsq(obs, mod)
#[1] 0.8560185

How to construct a WebSocket URI relative to the page URI?

If your Web server has support for WebSockets (or a WebSocket handler module) then you can use the same host and port and just change the scheme like you are showing. There are many options for running a Web server and Websocket server/module together.

I would suggest that you look at the individual pieces of the window.location global and join them back together instead of doing blind string substitution.

var loc = window.location, new_uri;
if (loc.protocol === "https:") {
    new_uri = "wss:";
} else {
    new_uri = "ws:";
}
new_uri += "//" + loc.host;
new_uri += loc.pathname + "/to/ws";

Note that some web servers (i.e. Jetty based ones) currently use the path (rather than the upgrade header) to determine whether a specific request should be passed on to the WebSocket handler. So you may be limited in whether you can transform the path in the way you want.

accessing a docker container from another container

It's easy. If you have two or more running container, complete next steps:

docker network create myNetwork
docker network connect myNetwork web1
docker network connect myNetwork web2

Now you connect from web1 to web2 container or the other way round.

Use the internal network IP addresses which you can find by running:

docker network inspect myNetwork

Note that only internal IP addresses and ports are accessible to the containers connected by the network bridge.

So for example assuming that web1 container was started with: docker run -p 80:8888 web1 (meaning that its server is running on port 8888 internally), and inspecting myNetwork shows that web1's IP is 172.0.0.2, you can connect from web2 to web1 using curl 172.0.0.2:8888).

Validate Dynamically Added Input fields

In case you have a form you can add a class name as such:

<form id="my-form">
  <input class="js-input" type="text" name="samplename" />
  <input class="js-input" type="text" name="samplename" />
  <input class="submit" type="submit" value="Submit" />
</form>

you can then use the addClassRules method of validator to add your rules like this and this will apply to all the dynamically added inputs:

$(document).ready(function() {
  $.validator.addClassRules('js-input', {
    required: true,
  });
  //validate the form
  $('#my-form').validate();
});

go get results in 'terminal prompts disabled' error for github private repo

go get disables the "terminal prompt" by default. This can be changed by setting an environment variable of git:

env GIT_TERMINAL_PROMPT=1 go get github.com/examplesite/myprivaterepo

Update OpenSSL on OS X with Homebrew

I had problems installing some Wordpress plugins on my local server running php56 on OSX10.11. They failed connection on the external API over SSL.

Installing openSSL didn't solved my problem. But then I figured out that CURL also needed to be reinstalled.

This solved my problem using Homebrew.

brew rm curl && brew install curl --with-openssl

brew uninstall php56 && brew install php56 --with-homebrew-curl --with-openssl

Console errors. Failed to load resource: net::ERR_INSECURE_RESPONSE

I am assuming you're using Chrome.

If so, the root problem is a certificate mismatch / expired certificate.

You can see this for yourself in the code here.

Note in particular the use of the very constant you reference in the code on line 48 of the C++ file I sent you:

 case net::ERR_INSECURE_RESPONSE:

The current version of this file is here. The error status ERR_INSECURE_RESPONSE may not any longer be on line 48 but the error code still exists in the SSL certificate portion of the code.

Note: Make sure to use the hostname which is listed in the SSL certificate, chrome automatically switches to the right hostname if you are browsing but not when using javascript.

What is the "Temporary ASP.NET Files" folder for?

The CLR uses it when it is compiling at runtime. Here is a link to MSDN that explains further.

When should I use Memcache instead of Memcached?

When using Windows, the comparison is cut short: memcache appears to be the only client available.

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

This has happened to me also, after undating to IOS11 on my iPhone. When I try to connect to the corporate network it bring up the corporate cert and says it isn't trusted. I press the 'trust' button and the connection fails and the cert does not appear in the trusted certs list.

Differences Between vbLf, vbCrLf & vbCr Constants

The three constants have similar functions nowadays, but different historical origins, and very occasionally you may be required to use one or the other.

You need to think back to the days of old manual typewriters to get the origins of this. There are two distinct actions needed to start a new line of text:

  1. move the typing head back to the left. In practice in a typewriter this is done by moving the roll which carries the paper (the "carriage") all the way back to the right -- the typing head is fixed. This is a carriage return.
  2. move the paper up by the width of one line. This is a line feed.

In computers, these two actions are represented by two different characters - carriage return is CR, ASCII character 13, vbCr; line feed is LF, ASCII character 10, vbLf. In the old days of teletypes and line printers, the printer needed to be sent these two characters -- traditionally in the sequence CRLF -- to start a new line, and so the CRLF combination -- vbCrLf -- became a traditional line ending sequence, in some computing environments.

The problem was, of course, that it made just as much sense to only use one character to mark the line ending, and have the terminal or printer perform both the carriage return and line feed actions automatically. And so before you knew it, we had 3 different valid line endings: LF alone (used in Unix and Macintoshes), CR alone (apparently used in older Mac OSes) and the CRLF combination (used in DOS, and hence in Windows). This in turn led to the complications of DOS / Windows programs having the option of opening files in text mode, where any CRLF pair read from the file was converted to a single CR (and vice versa when writing).

So - to cut a (much too) long story short - there are historical reasons for the existence of the three separate line separators, which are now often irrelevant: and perhaps the best course of action in .NET is to use Environment.NewLine which means someone else has decided for you which to use, and future portability issues should be reduced.

Install msi with msiexec in a Specific Directory

I tried TARGETDIR, INSTALLLOCATION and INSTALLDIR args and still it installed in the default directory. So I viewed the log and there is this arg where it sets the Application Directory and it is being set to default.

MSI (s) (50:94) [09:03:13:374]: Running product '{BDAFD18D-0395-4E72-B295-1EA66A7B80CF}' with elevated privileges: Product is assigned.
MSI (s) (50:94) [09:03:13:374]: PROPERTY CHANGE: Adding APPDIR property. Its value is 'E:\RMP2'.
MSI (s) (50:94) [09:03:13:374]: PROPERTY CHANGE: Adding CURRENTDIRECTORY property. Its value is 'C:\Users\Administrator'.

So I changed the command to have APPDIR instead of the args mentioned above. It worked like a charm.

msiexec /i "path_to_msi" APPDIR="path_to_installation_dir" /q

Add /lv if you want to copy the installation progress to a logfile.

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

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

Try

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

Angular ng-class if else

Just make a rule for each case:

<div id="homePage" ng-class="{ 'center': page.isSelected(1) , 'left': !page.isSelected(1)  }">

Or use the ternary operator:

<div id="homePage" ng-class="page.isSelected(1) ? 'center' : 'left'">

Fastest check if row exists in PostgreSQL

If you think about the performace ,may be you can use "PERFORM" in a function just like this:

 PERFORM 1 FROM skytf.test_2 WHERE id=i LIMIT 1;
  IF FOUND THEN
      RAISE NOTICE ' found record id=%', i;  
  ELSE
      RAISE NOTICE ' not found record id=%', i;  
 END IF;

Get first and last day of month using threeten, LocalDate

YearMonth

For completeness, and more elegant in my opinion, see this use of YearMonth class.

YearMonth month = YearMonth.from(date);
LocalDate start = month.atDay(1);
LocalDate end   = month.atEndOfMonth();

For the first & last day of the current month, this becomes:

LocalDate start = YearMonth.now().atDay(1);
LocalDate end   = YearMonth.now().atEndOfMonth();

What is the idiomatic Go equivalent of C's ternary operator?

Suppose you have the following ternary expression (in C):

int a = test ? 1 : 2;

The idiomatic approach in Go would be to simply use an if block:

var a int

if test {
  a = 1
} else {
  a = 2
}

However, that might not fit your requirements. In my case, I needed an inline expression for a code generation template.

I used an immediately evaluated anonymous function:

a := func() int { if test { return 1 } else { return 2 } }()

This ensures that both branches are not evaluated as well.

What is Join() in jQuery?

A practical example using a jQuery example might be

 var today = new Date();
 $('#'+[today.getMonth()+1, today.getDate(), today.getFullYear()].join("_")).whatever();

I do that in a calendar tool that I am using, this way on the page load, I can do certain things with today's date.

VB.NET Switch Statement GoTo Case

Select Case parameter
    ' does something here.
    ' does something here.
    Case "userID", "packageID", "mvrType"
                ' does something here.
        If otherFactor Then
        Else
            goto case default
        End If
    Case Else
        ' does some processing...
        Exit Select
End Select

How can I find where I will be redirected using cURL?

Add this line to curl inizialization

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

and use getinfo before curl_close

$redirectURL = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL );

es:

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0); 
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$html = curl_exec($ch);
$redirectURL = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL );
curl_close($ch);

How do I rotate text in css?

In your case, it's the best to use rotate option from transform property as mentioned before. There is also writing-mode property and it works like rotate(90deg) so in your case, it should be rotated after it's applied. Even it's not the right solution in this case but you should be aware of this property.

Example:

writing-mode:vertical-rl;

More about transform: https://kolosek.com/css-transform/

More about writing-mode: https://css-tricks.com/almanac/properties/w/writing-mode/

Sorting string array in C#

Actually I don't see any nulls:

given:

static void Main()
        {
            string[] testArray = new string[]
            {
                "aa",
                "ab",
                "ac",
                "ad",
                "ab",
                "af"
            };

            Array.Sort(testArray, StringComparer.InvariantCulture);

            Array.ForEach(testArray, x => Console.WriteLine(x));
        }

I obtained:

enter image description here

Warning: A non-numeric value encountered

If non-numeric value encountered in your code try below one. The below code is converted to float.

$PlannedAmount = ''; // empty string ''

if(!is_numeric($PlannedAmount)) {
           $PlannedAmount = floatval($PlannedAmount);
 }

 echo $PlannedAmount; //output = 0

HTML table with fixed headers?

A lot of people seem to be looking for this answer. I found it buried in an answer to another question here: Syncing column width of between tables in two different frames, etc

Of the dozens of methods I have tried this is the only method I found that works reliably to allow you to have a scrolling bottom table with the header table having the same widths.

Here is how I did it, first I improved upon the jsfiddle above to create this function, which works on both td and th (in case that trips up others who use th for styling of their header rows).

var setHeaderTableWidth= function (headertableid,basetableid) {
            $("#"+headertableid).width($("#"+basetableid).width());
            $("#"+headertableid+" tr th").each(function (i) {
                $(this).width($($("#"+basetableid+" tr:first td")[i]).width());
            });
            $("#" + headertableid + " tr td").each(function (i) {
                $(this).width($($("#" + basetableid + " tr:first td")[i]).width());
            });
        }

Next, you need to create two tables, NOTE the header table should have an extra TD to leave room in the top table for the scrollbar, like this:

 <table id="headertable1" class="input-cells table-striped">
        <thead>
            <tr style="background-color:darkgray;color:white;"><th>header1</th><th>header2</th><th>header3</th><th>header4</th><th>header5</th><th>header6</th><th></th></tr>
        </thead>
     </table>
    <div id="resizeToBottom" style="overflow-y:scroll;overflow-x:hidden;">
        <table id="basetable1" class="input-cells table-striped">
            <tbody >
                <tr>
                    <td>testdata</td>
                    <td>2</td>
                    <td>3</td>
                    <td>4</span></td>
                    <td>55555555555555</td>
                    <td>test</td></tr>
            </tbody>
        </table>
    </div>

Then do something like:

        setHeaderTableWidth('headertable1', 'basetable1');
        $(window).resize(function () {
            setHeaderTableWidth('headertable1', 'basetable1');
        });

This is the only solution that I found on Stack Overflow that works out of many similar questions that have been posted, that works in all my cases.

For example, I tried the jQuery stickytables plugin which does not work with durandal, and the Google Code project here https://code.google.com/p/js-scroll-table-header/issues/detail?id=2

Other solutions involving cloning the tables, have poor performance, or suck and don't work in all cases.

There is no need for these overly complex solutions. Just make two tables like the examples below and call setHeaderTableWidth function like described here and boom, you are done.

If this does not work for you, you probably were playing with your CSS box-sizing property and you need to set it correctly. It is easy to screw up your CSS content by accident. There are many things that can go wrong, so just be aware/careful of that. This approach works for me.

Install numpy on python3.3 - Install pip for python3

I'm on Ubuntu 15.04. This seemed to work:

$ sudo pip3 install numpy

On RHEL this worked:

$ sudo python3 -m pip install numpy

Force Internet Explorer to use a specific Java Runtime Environment install?

I'd give all the responses here a try first. But I wanted to just throw in what I do, just in case these do not work for you.

I've tried to solve the same problem you're having before, and in the end, what I decided on doing is to have only one JRE installed on my system at a given time. I do have about 10 different JDKs (1.3 through 1.6, and from various vendors - Sun, Oracle, IBM), since I do need it for development, but only one standalone JRE.

This has worked for me on my Windows 2000 + IE 6 computer at home, as well as my Windows XP + Multiple IE computer at work.

Automatically accept all SDK licences

Here is my Docker setup.
You can follow from a plain Linux environment.

Note that yes | and --licenses --sdk_root=${ANDROID_HOME} clauses.
It seems sdkmanager --update reverts agreements, so yes | is appeared twice.

FROM openjdk:8
# Install dev-essential(gnumake)
RUN apt update
RUN apt install -y build-essential
# Set ENV
ENV SDK_URL="https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip" \
    ANDROID_HOME="/usr/local/android-sdk" \
    ANDROID_VERSION=28 \
    ANDROID_BUILD_TOOLS_VERSION=28.0.3 \
    GRADLE_VERSION=4.10.3 \
    NDK_VERSION=r16b
# Download Android SDK
RUN mkdir "$ANDROID_HOME" .android \
    && cd "$ANDROID_HOME" \
    && curl -o sdk.zip $SDK_URL \
    && unzip sdk.zip \
    && rm sdk.zip \
    && yes | $ANDROID_HOME/tools/bin/sdkmanager --licenses --sdk_root=${ANDROID_HOME}
# Install Android Build Tool and Libraries
RUN $ANDROID_HOME/tools/bin/sdkmanager --update
RUN yes | $ANDROID_HOME/tools/bin/sdkmanager "build-tools;${ANDROID_BUILD_TOOLS_VERSION}" \
    "platforms;android-${ANDROID_VERSION}" \
    "platform-tools" --sdk_root=${ANDROID_HOME}
# Install Gradle
RUN wget https://services.gradle.org/distributions/gradle-${GRADLE_VERSION}-all.zip
RUN mkdir /opt/gradle
RUN unzip gradle-${GRADLE_VERSION}-all.zip -d /opt/gradle
ENV PATH=${PATH}:/opt/gradle/gradle-${GRADLE_VERSION}/bin
# Install NDK
RUN wget https://dl.google.com/android/repository/android-ndk-${NDK_VERSION}-linux-x86_64.zip
RUN mkdir /opt/ndk-bundle
RUN unzip android-ndk-${NDK_VERSION}-linux-x86_64.zip -d /opt/ndk-bundle
ENV PATH=${PATH}:/opt/ndk-bundle

RUN mkdir /application
WORKDIR /application

How to use Checkbox inside Select Option

Use this code for checkbox list on option menu.

_x000D_
_x000D_
.dropdown-menu input {_x000D_
   margin-right: 10px;_x000D_
}   
_x000D_
<div class="btn-group">_x000D_
    <a href="#" class="btn btn-primary"><i class="fa fa-cogs"></i></a>_x000D_
    <a href="#" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">_x000D_
      <span class="caret"></span>_x000D_
    </a>_x000D_
    <ul class="dropdown-menu" style="padding: 10px" id="myDiv">_x000D_
        <li><p><input type="checkbox" value="id1" > OA Number</p></li>_x000D_
        <li><p><input type="checkbox" value="id2" >Customer</p></li>_x000D_
        <li><p><input type="checkbox" value="id3" > OA Date</p></li>_x000D_
        <li><p><input type="checkbox" value="id4" >Product Code</p></li>_x000D_
        <li><p><input type="checkbox" value="id5" >Name</p></li>_x000D_
        <li><p><input type="checkbox" value="id6" >WI Number</p></li>_x000D_
        <li><p><input type="checkbox" value="id7" >WI QTY</p></li>_x000D_
        <li><p><input type="checkbox" value="id8" >Production QTY</p></li>_x000D_
        <li><p><input type="checkbox" value="id9" >PD Sr.No (from-to)</p></li>_x000D_
        <li><p><input type="checkbox" value="id10" > Production Date</p></li>_x000D_
        <button class="btn btn-info" onClick="showTable();">Go</button>_x000D_
    </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Is there an upper bound to BigInteger?

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

How to format date and time in Android?

Use the standard Java DateFormat class.

For example to display the current date and time do the following:

Date date = new Date(location.getTime());
DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
mTimeText.setText("Time: " + dateFormat.format(date));

You can initialise a Date object with your own values, however you should be aware that the constructors have been deprecated and you should really be using a Java Calendar object.

Setting up Vim for Python

Under Linux, What worked for me was John Anderson's (sontek) guide, which you can find at this link. However, I cheated and just used his easy configuration setup from his Git repostiory:

git clone -b vim https://github.com/sontek/dotfiles.git

cd dotfiles

./install.sh vim

His configuration is fairly up to date as of today.

convert a char* to std::string

Most answers talks about constructing std::string.

If already constructed, just use assignment operator.

std::string oString;
char* pStr;

... // Here allocate and get character string (e.g. using fgets as you mentioned)

oString = pStr; // This is it! It copies contents from pStr to oString

Repeat each row of data.frame the number of times specified in a column

In case you have to do this operation on very large data.frames I would recommend converting it into a data.table and use the following, which should run much faster:

library(data.table)
dt <- data.table(df)
dt.expanded <- dt[ ,list(freq=rep(1,freq)),by=c("var1","var2")]
dt.expanded[ ,freq := NULL]
dt.expanded

See how much faster this solution is:

df <- data.frame(var1=1:2e3, var2=1:2e3, freq=1:2e3)
system.time(df.exp <- df[rep(row.names(df), df$freq), 1:2])
##    user  system elapsed 
##    4.57    0.00    4.56
dt <- data.table(df)
system.time(dt.expanded <- dt[ ,list(freq=rep(1,freq)),by=c("var1","var2")])
##    user  system elapsed 
##    0.05    0.01    0.06

How to return part of string before a certain character?

In General a function to return string after substring is

_x000D_
_x000D_
function getStringAfterSubstring(parentString, substring) {_x000D_
    return parentString.substring(parentString.indexOf(substring) + substring.length)_x000D_
}_x000D_
_x000D_
function getStringBeforeSubstring(parentString, substring) {_x000D_
    return parentString.substring(0, parentString.indexOf(substring))_x000D_
}_x000D_
console.log(getStringAfterSubstring('abcxyz123uvw', '123'))_x000D_
console.log(getStringBeforeSubstring('abcxyz123uvw', '123'))
_x000D_
_x000D_
_x000D_

Select current element in jQuery

I think by combining .children() with $(this) will return the children of the selected item only

consider the following:

$("div li").click(function() {
$(this).children().css('background','red');
});

this will change the background of the clicked li only

node.js vs. meteor.js what's the difference?

Meteor is a framework built ontop of node.js. It uses node.js to deploy but has several differences.

The key being it uses its own packaging system instead of node's module based system. It makes it easy to make web applications using Node. Node can be used for a variety of things and on its own is terrible at serving up dynamic web content. Meteor's libraries make all of this easy.

Is there any ASCII character for <br>?

<br> is an HTML element. There isn't any ASCII code for it.

But, for line break sometimes &#013; is used as the text code.

Or &lt;br&gt;

You can check the text code here.

Concatenation of strings in Lua

Strings can be joined together using the concatenation operator ".."

this is the same for variables I think

How can I loop through a C++ map of maps?

for(std::map<std::string, std::map<std::string, std::string> >::iterator outer_iter=map.begin(); outer_iter!=map.end(); ++outer_iter) {
    for(std::map<std::string, std::string>::iterator inner_iter=outer_iter->second.begin(); inner_iter!=outer_iter->second.end(); ++inner_iter) {
        std::cout << inner_iter->second << std::endl;
    }
}

or nicer in C++0x:

for(auto outer_iter=map.begin(); outer_iter!=map.end(); ++outer_iter) {
    for(auto inner_iter=outer_iter->second.begin(); inner_iter!=outer_iter->second.end(); ++inner_iter) {
        std::cout << inner_iter->second << std::endl;
    }
}

How to convert Hexadecimal #FFFFFF to System.Drawing.Color

Remove the '#' and do

Color c = Color.FromArgb(int.Parse("#FFFFFF".Replace("#",""),
                         System.Globalization.NumberStyles.AllowHexSpecifier));

TLS 1.2 not working in cURL

Replace following

curl_setopt ($setuploginurl, CURLOPT_SSLVERSION, 'CURL_SSLVERSION_TLSv1_2');

With

curl_setopt ($ch, CURLOPT_SSLVERSION, 6);

Should work flawlessly.

How do I create a multiline Python string with inline variables?

This is what you want:

>>> string1 = "go"
>>> string2 = "now"
>>> string3 = "great"
>>> mystring = """
... I will {string1} there
... I will go {string2}
... {string3}
... """
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, 'string3': 'great', '__package__': None, 'mystring': "\nI will {string1} there\nI will go {string2}\n{string3}\n", '__name__': '__main__', 'string2': 'now', '__doc__': None, 'string1': 'go'}
>>> print(mystring.format(**locals()))

I will go there
I will go now
great

How to create RecyclerView with multiple view type?

Yes, it's possible. Just implement getItemViewType(), and take care of the viewType parameter in onCreateViewHolder().

So you do something like:

public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    class ViewHolder0 extends RecyclerView.ViewHolder {
        ...
        public ViewHolder0(View itemView){
        ...
        }
    }

    class ViewHolder2 extends RecyclerView.ViewHolder {
        ...
        public ViewHolder2(View itemView){
        ...
    }

    @Override
    public int getItemViewType(int position) {
        // Just as an example, return 0 or 2 depending on position
        // Note that unlike in ListView adapters, types don't have to be contiguous
        return position % 2 * 2;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
         switch (viewType) {
             case 0: return new ViewHolder0(...);
             case 2: return new ViewHolder2(...);
             ...
         }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        switch (holder.getItemViewType()) {
            case 0:
                ViewHolder0 viewHolder0 = (ViewHolder0)holder;
                ...
                break;

            case 2:
                ViewHolder2 viewHolder2 = (ViewHolder2)holder;
                ...
                break;
        }
    }
}

How to handle authentication popup with Selenium WebDriver using Java

This should work for Firefox by using AutoAuth plugin:

FirefoxProfile firefoxProfile = new ProfilesIni().getProfile("default");
File ffPluginAutoAuth = new File("D:\\autoauth-2.1-fx+fn.xpi");
firefoxProfile.addExtension(ffPluginAutoAuth);
driver = new FirefoxDriver(firefoxProfile);

Excel VBA Macro: User Defined Type Not Defined

Sub DeleteEmptyRows()  

    Worksheets("YourSheetName").Activate
    On Error Resume Next
    Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

End Sub

The following code will delete all rows on a sheet(YourSheetName) where the content of Column A is blank.

EDIT: User Defined Type Not Defined is caused by "oTable As Table" and "oRow As Row". Replace Table and Row with Object to resolve the error and make it compile.

Error when trying vagrant up

edit the vagrant file created by vagrant init in the same directory and enter the box name in the line config.vm.box = "ubuntu/trusty64" where ubuntu/trusty64 is your base box. Now vagrant up will download and set ubuntu/trusty64 as base box for you.

Run parallel multiple commands at once in the same terminal

Use GNU Parallel:

(echo command1; echo command2) | parallel
parallel ::: command1 command2

To kill:

parallel ::: command1 command2 &
PID=$!
kill -TERM $PID
kill -TERM $PID

Python 3 turn range to a list

In fact, this is a retro-gradation of Python3 as compared to Python2. Certainly, Python2 which uses range() and xrange() is more convenient than Python3 which uses list(range()) and range() respectively. The reason is because the original designer of Python3 is not very experienced, they only considered the use of the range function by many beginners to iterate over a large number of elements where it is both memory and CPU inefficient; but they neglected the use of the range function to produce a number list. Now, it is too late for them to change back already.

If I was to be the designer of Python3, I will:

  1. use irange to return a sequence iterator
  2. use lrange to return a sequence list
  3. use range to return either a sequence iterator (if the number of elements is large, e.g., range(9999999) or a sequence list (if the number of elements is small, e.g., range(10))

That should be optimal.

How to create an empty DataFrame with a specified schema?

This is helpful for testing purposes.

Seq.empty[String].toDF()

Open a local HTML file using window.open in Chrome

window.location.href = 'file://///fileserver/upload/Old_Upload/05_06_2019/THRESHOLD/BBH/Look/chrs/Delia';

Nothing Worked for me.

How to change the Content of a <textarea> with JavaScript

If it's jQuery...

$("#myText").val('');

or

document.getElementById('myText').value = '';

Reference: Text Area Object

How can I check Drupal log files?

We can use drush command also to check logs drush watchdog-show it will show recent 10 messages.

or if we want to continue showing logs with more information we can user

drush watchdog-show --tail --full.

Get the current first responder without using a private API

Just it case here is Swift version of awesome Jakob Egger's approach:

import UIKit

private weak var currentFirstResponder: UIResponder?

extension UIResponder {

    static func firstResponder() -> UIResponder? {
        currentFirstResponder = nil
        UIApplication.sharedApplication().sendAction(#selector(self.findFirstResponder(_:)), to: nil, from: nil, forEvent: nil)
        return currentFirstResponder
    }

    func findFirstResponder(sender: AnyObject) {
        currentFirstResponder = self
    }

}

How do I refresh the page in ASP.NET? (Let it reload itself by code)

There are various method to refresh the page in asp.net like...

Java Script

 function reloadPage()
 {
     window.location.reload()
 }

Code Behind

Response.Redirect(Request.RawUrl)

Meta Tag

<meta http-equiv="refresh" content="600"></meta>

Page Redirection

Response.Redirect("~/default.aspx"); // Or whatever your page url

How to change the scrollbar color using css

Your css will only work in IE browser. And the css suggessted by hayk.mart will olny work in webkit browsers. And by using different css hacks you can't style your browsers scroll bars with a same result.

So, it is better to use a jQuery/Javascript plugin to achieve a cross browser solution with a same result.

Solution:

By Using jScrollPane a jQuery plugin, you can achieve a cross browser solution

See This Demo

How to search contents of multiple pdf files?

There is an open source common resource grep tool crgrep which searches within PDF files but also other resources like content nested in archives, database tables, image meta-data, POM file dependencies and web resources - and combinations of these including recursive search.

The full description under the Files tab pretty much covers what the tool supports.

I developed crgrep as an opensource tool.

TypeLoadException says 'no implementation', but it is implemented

I received this error after a recent windows update. I had a service class set to inherit from an interface. The interface contained a signature that returned a ValueTuple, a fairly new feature in C#.

All I can guess is that the windows update installed a new one, but even explicitly referencing it, updating binding redirects, etc...The end result was just changing the signature of the method to something "standard" I guess you could say.

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

Thanks Friend, i got an answer. This is only possible because of your help. you all give me a ray of hope towards resolving this problem.

Here is the code:

package facebook;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class Facebook {
    public static void main(String args[]){
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.facebook.com");
        WebElement email= driver.findElement(By.id("email"));
        Actions builder = new Actions(driver);
        Actions seriesOfActions = builder.moveToElement(email).click().sendKeys(email, "[email protected]");
        seriesOfActions.perform();
        WebElement pass = driver.findElement(By.id("pass"));
        WebElement login =driver.findElement(By.id("u_0_b"));
        Actions seriesOfAction = builder.moveToElement(pass).click().sendKeys(pass, "naveench").click(login);
        seriesOfAction.perform();
        driver.
    }    
}

Is it possible to do a sparse checkout without checking out the whole repository first?

Sadly none of the above worked for me so I spent very long time trying different combination of sparse-checkout file.

In my case I wanted to skip folders with IntelliJ IDEA configs.

Here is what I did:


Run git clone https://github.com/myaccount/myrepo.git --no-checkout

Run git config core.sparsecheckout true

Created .git\info\sparse-checkout with following content

!.idea/*
!.idea_modules/*
/*

Run 'git checkout --' to get all files.


Critical thing to make it work was to add /* after folder's name.

I have git 1.9

Writing to a new file if it doesn't exist, and appending to a file if it does

Notice that if the file's parent folder doesn't exist you'll get the same error:

IOError: [Errno 2] No such file or directory:

Below is another solution which handles this case:
(*) I used sys.stdout and print instead of f.write just to show another use case

# Make sure the file's folder exist - Create folder if doesn't exist
folder_path = 'path/to/'+folder_name+'/'
if not os.path.exists(folder_path):
     os.makedirs(folder_path)

print_to_log_file(folder_path, "Some File" ,"Some Content")

Where the internal print_to_log_file just take care of the file level:

# If you're not familiar with sys.stdout - just ignore it below (just a use case example)
def print_to_log_file(folder_path ,file_name ,content_to_write):

   #1) Save a reference to the original standard output       
    original_stdout = sys.stdout   
    
    #2) Choose the mode
    write_append_mode = 'a' #Append mode
    file_path = folder_path + file_name
    if (if not os.path.exists(file_path) ):
       write_append_mode = 'w' # Write mode
     
    #3) Perform action on file
    with open(file_path, write_append_mode) as f:
        sys.stdout = f  # Change the standard output to the file we created.
        print(file_path, content_to_write)
        sys.stdout = original_stdout  # Reset the standard output to its original value

Consider the following states:

'w'  --> Write to existing file
'w+' --> Write to file, Create it if doesn't exist
'a'  --> Append to file
'a+' --> Append to file, Create it if doesn't exist

In your case I would use a different approach and just use 'a' and 'a+'.

Maven Jacoco Configuration - Exclude classes/packages from report not working

Your XML is slightly wrong, you need to add any class exclusions within an excludes parent field, so your above configuration should look like the following as per the Jacoco docs

<configuration>
    <excludes>
        <exclude>**/*Config.*</exclude>
        <exclude>**/*Dev.*</exclude>
    </excludes>
</configuration>

The values of the exclude fields should be class paths (not package names) of the compiled classes relative to the directory target/classes/ using the standard wildcard syntax

*   Match zero or more characters
**  Match zero or more directories
?   Match a single character

You may also exclude a package and all of its children/subpackages this way:

<exclude>some/package/**/*</exclude>

This will exclude every class in some.package, as well as any children. For example, some.package.child wouldn't be included in the reports either.

I have tested and my report goal reports on a reduced number of classes using the above.

If you are then pushing this report into Sonar, you will then need to tell Sonar to exclude these classes in the display which can be done in the Sonar settings

Settings > General Settings > Exclusions > Code Coverage

Sonar Docs explains it a bit more

Running your command above

mvn clean verify

Will show the classes have been excluded

No exclusions

[INFO] --- jacoco-maven-plugin:0.7.4.201502262128:report (post-test) @ ** ---
[INFO] Analyzed bundle '**' with 37 classes

With exclusions

[INFO] --- jacoco-maven-plugin:0.7.4.201502262128:report (post-test) @ ** ---
[INFO] Analyzed bundle '**' with 34 classes

Hope this helps

Can I force a page break in HTML printing?

CSS

@media print {
  .pagebreak { 
     page-break-before: always; 
  }
}

HTML

<div class="pagebreak"></div>

Is there a way to set background-image as a base64 encoded image?

I tried to do the same as you, but apparently the backgroundImage doesn't work with encoded data. As an alternative, I suggest to use CSS classes and the change between those classes.

If you are generating the data "on the fly" you can load the CSS files dynamically.

CSS:

.backgroundA {
    background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAIAAACRXR/mAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2giIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6RDUxRjY0ODgyQTkxMTFFMjk0RkU5NjI5MEVDQTI2QzUiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6RDUxRjY0ODkyQTkxMTFFMjk0RkU5NjI5MEVDQTI2QzUiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpENTFGNjQ4NjJBOTExMUUyOTRGRTk2MjkwRUNBMjZDNSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpENTFGNjQ4NzJBOTExMUUyOTRGRTk2MjkwRUNBMjZDNSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PuT868wAAABESURBVHja7M4xEQAwDAOxuPw5uwi6ZeigB/CntJ2lkmytznwZFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYW1qsrwABYuwNkimqm3gAAAABJRU5ErkJggg==");
}

.backgroundB {
    background-image:url("data:image/gif;base64,R0lGODlhUAAPAKIAAAsLav///88PD9WqsYmApmZmZtZfYmdakyH5BAQUAP8ALAAAAABQAA8AAAPbWLrc/jDKSVe4OOvNu/9gqARDSRBHegyGMahqO4R0bQcjIQ8E4BMCQc930JluyGRmdAAcdiigMLVrApTYWy5FKM1IQe+Mp+L4rphz+qIOBAUYeCY4p2tGrJZeH9y79mZsawFoaIRxF3JyiYxuHiMGb5KTkpFvZj4ZbYeCiXaOiKBwnxh4fnt9e3ktgZyHhrChinONs3cFAShFF2JhvCZlG5uchYNun5eedRxMAF15XEFRXgZWWdciuM8GCmdSQ84lLQfY5R14wDB5Lyon4ubwS7jx9NcV9/j5+g4JADs=");
}

HTML:

<div id="test" height="20px" class="backgroundA"> 
  div test 1
</div>
<div id="test2" name="test2" height="20px" class="backgroundB">
  div test2
</div>
<input type="button" id="btn" />

Javascript:

function change() {
    if (document.getElementById("test").className =="backgroundA") {
        document.getElementById("test").className="backgroundB";
        document.getElementById("test2").className="backgroundA";
    } else {
        document.getElementById("test").className="backgroundA";
        document.getElementById("test2").className="backgroundB";
    }
}

btn.onclick= change;

I fiddled it here, press the button and it will switch the divs' backgrounds: http://jsfiddle.net/egorbatik/fFQC6/

Linq where clause compare only date value without time value

Working code :

     {
        DataBaseEntity db = new DataBaseEntity (); //This is EF entity
        string dateCheck="5/21/2018";
        var list= db.tbl
        .where(x=>(x.DOE.Value.Month
              +"/"+x.DOE.Value.Day
              +"/"+x.DOE.Value.Year)
             .ToString()
             .Contains(dateCheck))
     }

Batch file. Delete all files and folders in a directory

@echo off
@color 0A

echo Deleting logs

rmdir /S/Q c:\log\

ping 1.1.1.1 -n 5 -w 1000 > nul

echo Adding log folder back

md c:\log\

You was on the right track. Just add code to add the folder which is deleted back again.

Git merge is not possible because I have unmerged files

I ran into the same issue and couldn't decide between laughing or smashing my head on the table when I read this error...

What git really tries to tell you: "You are already in a merge state and need to resolve the conflicts there first!"

You tried a merge and a conflict occured. Then, git stays in the merge state and if you want to resolve the merge with other commands git thinks you want to execute a new merge and so it tells you you can't do this because of your current unmerged files...

You can leave this state with git merge --abort and now try to execute other commands.

In my case I tried a pull and wanted to resolve the conflicts by hand when the error occured...

Wireshark localhost traffic capture

I haven't actually tried this, but this answer from the web sounds promising:

Wireshark can't actually capture local packets on windows XP due to the nature of the windows TCP stack. When packets are sent and received on the same machine they don't seem to cross the network boundary that wireshark monitors.

However there is a way around this, you can route the local traffic out via your network gateway (router) by setting up a (temporary) static route on your windows XP machine.

Say your XP IP address is 192.168.0.2 and your gateway (router) address is 192.168.0.1 you could run the following command from windows XP command line to force all local traffic out and back across the network boundary, so wireshark could then track the data (note that wireshark will report packets twice in this scenario, once when they leave your pc and once when they return).

route add 192.168.0.2 mask 255.255.255.255 192.168.0.1 metric 1

http://forums.whirlpool.net.au/archive/1037087, accessed just now.

How do you get the logical xor of two variables in Python?

If you're already normalizing the inputs to booleans, then != is xor.

bool(a) != bool(b)

How to convert numbers to words without using num2word library?

    def giveText(num):
    pairs={1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',10:'ten',
    11:'eleven',12:'twelve',13:'thirteen',14:'fourteen',15:'fifteen',16:'sixteen',17:'seventeen',18:'eighteen',19:'nineteen',20:'twenty',
    30:'thirty',40:'fourty',50:'fifty',60:'sixty',70:'seventy',80:'eighty',90:'ninety',0:''} # this and above 2 lines are actually single line
    return pairs[num]

def toText(num,unit):
    n=int(num)# this line can be removed
    ans=""
    if n <=20:
        ans= giveText(n)
    else:
        ans= giveText(n-(n%10))+" "+giveText((n%10))
    ans=ans.strip()
    if len(ans)>0:
        return " "+ans+" "+unit
    else:
        return " "

num="99,99,99,999"# use raw_input()
num=num.replace(",","")# to remove ','
try:
    num=str(int(num)) # to check valid number
except:
    print "Invalid"
    exit()

while len(num)<9: # i want fix length so no need to check it again
    num="0"+num

ans=toText( num[0:2],"Crore")+toText(num[2:4],"Lakh")+toText(num[4:6],"Thousand")+toText(num[6:7],"Hundred")+toText(num[7:9],"")
print ans.strip()

How to communicate between iframe and the parent site?

Use event.source.window.postMessage to send back to sender.

From Iframe

window.top.postMessage('I am Iframe', '*')
window.onmessage = (event) => {
    if (event.data === 'GOT_YOU_IFRAME') {
        console.log('Parent received successfully.')
    }
}

Then from parent say back.

window.onmessage = (event) => {
    event.source.window.postMessage('GOT_YOU_IFRAME', '*')
}

PostgreSQL: Show tables in PostgreSQL

  1. First login as postgres user:

    sudo su - postgres

  2. connect to the required db: psql -d databaseName

  3. \dt would return the list of all table in the database you're connected to.

Adding iOS UITableView HeaderView (not section header)

UITableView has a tableHeaderView property. Set that to whatever view you want up there.

Use a new UIView as a container, add a text label and an image view to that new UIView, then set tableHeaderView to the new view.

For example, in a UITableViewController:

-(void)viewDidLoad
{
     // ...
     UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(XXX, YYY, XXX, YYY)];
     UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(XXX, YYY, XXX, YYY)];
     [headerView addSubview:imageView];
     UILabel *labelView = [[UILabel alloc] initWithFrame:CGRectMake(XXX, YYY, XXX, YYY)];
     [headerView addSubview:labelView];
     self.tableView.tableHeaderView = headerView;
     [imageView release];
     [labelView release];
     [headerView release];
     // ...
} 

Is there an easy way to strike through text in an app widget?

Another way to do it programmatically which looks a bit less like a hack than the Paint way:

Instead of doing:

tv.setText(s);

do:

private static final StrikethroughSpan STRIKE_THROUGH_SPAN = new StrikethroughSpan();
...
tv.setText(s, TextView.BufferType.SPANNABLE);
Spannable spannable = (Spannable) tv.getText();
spannable.setSpan(STRIKE_THROUGH_SPAN, 0, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

How can I scale the content of an iframe?

You don't need to wrap the iframe with an additional tag. Just make sure you increase the width and height of the iframe by the same amount you scale down the iframe.

e.g. to scale the iframe content to 80% :

#frame { /* Example size! */
    height: 400px; /* original height */
    width: 100%; /* original width */
}
#frame {
    height: 500px; /* new height (400 * (1/0.8) ) */
    width: 125%; /* new width (100 * (1/0.8) )*/

    transform: scale(0.8); 
    transform-origin: 0 0;
}

Basically, to get the same size iframe you need to scale the dimensions.

gnuplot plotting multiple line graphs

In addition to the answers above the command below will also work. I post it because it makes more sense to me. In each case it is 'using x-value-column: y-value-column'

plot 'ls.dat' using 1:2, 'ls.dat' using 1:3, 'ls.dat' using 1:4 

note that the command above assumes that you have a file named ls.dat with tab separated columns of data where column 1 is x, column 2 is y1, column 3 is y2 and column 4 is y3.

How do I setup the InternetExplorerDriver so it works

Unpack it and place somewhere you can find it. In my example, I will assume you will place it to C:\Selenium\iexploredriver.exe

Then you have to set it up in the system. Here is the Java code pasted from my Selenium project:

File file = new File("C:/Selenium/iexploredriver.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driver = new InternetExplorerDriver();

Basically, you have to set this property before you initialize driver

Reference:

Trigger change() event when setting <select>'s value with val() function

One thing that I found out (the hard way), is that you should have

$('#selectField').change(function(){
  // some content ...
});

defined BEFORE you are using

$('#selectField').val(10).trigger('change');

or

 $('#selectField').val(10).change();

Regular expression - starting and ending with a letter, accepting only letters, numbers and _

I'll take a stab at it:

/^[a-z](?:_?[a-z0-9]+)*$/i

Explained:

/
 ^           # match beginning of string
 [a-z]       # match a letter for the first char
 (?:         # start non-capture group
   _?          # match 0 or 1 '_'
   [a-z0-9]+   # match a letter or number, 1 or more times
 )*          # end non-capture group, match whole group 0 or more times
 $           # match end of string
/i           # case insensitive flag

The non-capture group takes care of a) not allowing two _'s (it forces at least one letter or number per group) and b) only allowing the last char to be a letter or number.

Some test strings:

"a": match
"_": fail
"zz": match
"a0": match
"A_": fail
"a0_b": match
"a__b": fail
"a_1_c": match

Div Scrollbar - Any way to style it?

Using javascript you can style the scroll bars. Which works fine in IE as well as FF.

Check the below links

From Twinhelix , Example 2 , Example 3 [or] you can find some 30 type of scroll style types by click the below link 30 scrolling techniques

How to insert an image in python

Install PIL(Python Image Library) :

then:

from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();

How to calculate sum of a formula field in crystal Reports?

(Assuming you are looking at the reports in the Crystal Report Designer...)

Your menu options might be a little different depending on the version of Crystal Reports you're using, but you can either:

  • Make a summary field: Right-click on the desired formula field in your detail section and choose "Insert Summary". Choose "sum" from the drop-down box and verify that the correct account grouping is selected, then click OK. You will then have a simple sum field in your group footer section.
  • Make a running total field: Click on the "Insert" menu and choose "Running Total Field..."*** Click on the New button and give your new running total field a name. Choose your formula field under "Field to summarize" and choose "sum" under "Type of Summary". Here you can also change when the total is evaluated and reset, leave these at their default if you're wanting a sum on each record. You can also use a formula to determine when a certain field should be counted in the total. (Evaluate: Use Formula)

Is there a way to use PhantomJS in Python?

The answer by @Pykler is great but the Node requirement is outdated. The comments in that answer suggest the simpler answer, which I've put here to save others time:

  1. Install PhantomJS

    As @Vivin-Paliath points out, it's a standalone project, not part of Node.

    Mac:

    brew install phantomjs
    

    Ubuntu:

    sudo apt-get install phantomjs
    

    etc

  2. Set up a virtualenv (if you haven't already):

    virtualenv mypy  # doesn't have to be "mypy". Can be anything.
    . mypy/bin/activate
    

    If your machine has both Python 2 and 3 you may need run virtualenv-3.6 mypy or similar.

  3. Install selenium:

    pip install selenium
    
  4. Try a simple test, like this borrowed from the docs:

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    
    driver = webdriver.PhantomJS()
    driver.get("http://www.python.org")
    assert "Python" in driver.title
    elem = driver.find_element_by_name("q")
    elem.clear()
    elem.send_keys("pycon")
    elem.send_keys(Keys.RETURN)
    assert "No results found." not in driver.page_source
    driver.close()
    

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

Old thread but for me it started working (after following all advise above) when i renamed int main(void) to int wmain(void) and removed WIN23 from cmake's add_executable().

Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag?

LINKS ARE TRICKY

Consider the tricks that <a href> knows by default but javascript linking won't do for you. On a decent website, anything that wants to behave as a link should implement these features one way or another. Namely:

  • Ctrl+Click: opens link in new tab
    You can simulate this by using a window.open() with no position/size argument
  • Shift+Click: opens link in new window
    You can simulate this by window.open() with size and/or position specified
  • Alt+Click: download target
    People rarely use this one, but if you insist to simulate it, you'll need to write a special script on server side that responds with the proper download headers.

EASY WAY OUT

Now if you don't want to simulate all that behaviour, I suggest to use <a href> and style it like a button, since the button itself is roughly a shape and a hover effect. I think if it's not semantically important to only have "the button and nothing else", <a href> is the way of the samurai. And if you worry about semantics and readability, you can also replace the button element when your document is ready(). It's clear and safe.

Can I fade in a background image (CSS: background-image) with jQuery?

I know i'm late, but I found a way using jquery which works on every browser(i tested it on chrome, firefox and Ie 9)and th fore-ground elements are always displayed instead of css3 transition property.

create 2 absolute wrapper and using z-index.

First set the elements that have to be in the fore-ground with the highest z-index property value, and the other elemets(all included in the body, so: body{}) with a lower z-index property value than the fore-ground elements'one , at least of 2 number lower.

HTML part:

         <div class="wrapper" id="wrapper1"></div>
         <div class="wrapper" id="wrapper2"></div>

css part:

        .fore-groundElements{              //select all fore-ground elements
                  z-index:0;               //>=0
        }
       .wrapper{
                  background-size: cover;
                  width:100%;
                  height:100%;
                  background-size: 100% 100%;
                  position:absolute;
         }

        #wrapper1{
               z-index:-1; 
        }


        #wrapper2{
                 z-index:-2;
         }
         body{

              height:100%;
              width:100%;
              margin:0px;   
              display:cover;
              z-index:-3                          //<=-3
         }

than the javascript/jquery one:

i needed to change the background image every three second so i used a set timeout.

this is the code:

  $(document).ready(main);

  var main = function(){

             var imgPath=[imagesPath1,..,...];                 // the array in which store the image paths

             var newWrapper;                     // the wrapper to display 
             var currentWrapper;                 //the current displayed wrapper which has to be faded
             var l=2;                             // the next image index  to be displayed, it is set to 2 because the first two position of the array(first two images) start already setted up
             var imgNumber= imgPath.length;        //to know when the images are over and restart the carousel
             var currentImg;                       //the next image path to be displayed


             $('#wrapper1').css("background-image", 'url'+imgPath[0]);         //pre set the first wrapper background images
             $('#wrapper2').css("background-image", 'url'+imgPath[1]);          //pre set the first wrapper background images   

             setInterval(myfunction,3000);                //refresh the background image every three seconds

             function myfunction(){
                    if(l===imgNumber-1){               //restart the carousel if every single image has already been displayed                  
                         l=0;
                     };

             if(l%2==0||l%2==2){                    //set the wrapper that will be displaied after the fadeOut callback function
                  currentWrapper='#wrapper1';         
                  newWrapper='#wrapper2';
             }else{
                  currentWrapper='#wrapper2';
                  newWrapper='#wrapper1';
             };
             currentImg=imgPath[l];
            $(currentWrapper).fadeOut(1000,function(){               //fade out the current wrapper, so now the back-ground wrapper is fully displayed
                  $(newWrapper).css("z-index", "-1");                //move the shown wrapper in the fore-ground
                  $(currentWrapper).css("z-index","-2");             //move the hidden wrapper in the back ground
                  $(currentWrapper).css("background-image",'url'+currentImg);                   // sets up the next image that is now shown in the actually hidden background wrapper
                  $(currentWrapper).show();          //shows the background wrapper, which is not visible yet, and it will be shown the next time the setInterval event will be triggered
                  l++;                         //set the next image index that will be set the next time the setInterval event will be triggered 
             });


         };                   //end of myFunction
  }                          //end of main

i hope that my answer is clear,if you need more explanation comment it.

sorry for my english :)

Get the string representation of a DOM node

I've found that for my use-cases I don't always want the entire outerHTML. Many nodes just have too many children to show.

Here's a function (minimally tested in Chrome):

/**
 * Stringifies a DOM node.
 * @param {Object} el - A DOM node.
 * @param {Number} truncate - How much to truncate innerHTML of element.
 * @returns {String} - A stringified node with attributes
 *                     retained.
 */
function stringifyEl(el, truncate) {
    var truncateLen = truncate || 50;
    var outerHTML = el.outerHTML;
    var ret = outerHTML;
    ret = ret.substring(0, truncateLen);

    // If we've truncated, add an elipsis.
    if (outerHTML.length > truncateLen) {
      ret += "...";
    }
    return ret;
}

https://gist.github.com/kahunacohen/467f5cc259b5d4a85eb201518dcb15ec

What is a .pid file and what does it contain?

The pid files contains the process id (a number) of a given program. For example, Apache HTTPD may write its main process number to a pid file - which is a regular text file, nothing more than that - and later use the information there contained to stop itself. You can also use that information to kill the process yourself, using cat filename.pid | xargs kill

Creating a PHP header/footer

Just create the header.php file, and where you want to use it do:

<?php
include('header.php');
?>

Same with the footer. You don't need php tags in these files if you just have html.

See more about include here:

http://php.net/manual/en/function.include.php

Initialize static variables in C++ class?

They can't be initialised inside the class, but they can be initialised outside the class, in a source file:

// inside the class
class Thing {
    static string RE_ANY;
    static string RE_ANY_RELUCTANT;
};

// in the source file
string Thing::RE_ANY = "([^\\n]*)";
string Thing::RE_ANY_RELUCTANT = "([^\\n]*?)";

Update

I've just noticed the first line of your question - you don't want to make those functions static, you want to make them const. Making them static means that they are no longer associated with an object (so they can't access any non-static members), and making the data static means it will be shared with all objects of this type. This may well not be what you want. Making them const simply means that they can't modify any members, but can still access them.

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:

NuGet

Up next is the create script. Creating a database file:

SQLiteConnection.CreateFile("MyDatabase.sqlite");

SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

m_dbConnection.Close();

After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
 {
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
     tran.Complete();
 }

Error on renaming database in SQL Server 2008 R2

Another way to close all connections:

Administrative Tools > View Local Services

Stop/Start the "SQL Server (MSSQLSERVER)" service

TCPDF Save file to folder?

Only thing that worked for me:

// save file
$pdf->Output(__DIR__ . '/example_001.pdf', 'F');
exit();

How to convert DataSet to DataTable

DataSet is collection of DataTables.... you can get the datatable from DataSet as below.

//here ds is dataset
DatTable dt = ds.Table[0]; /// table of dataset

for or while loop to do something n times

but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?

That is what xrange(n) is for. It avoids creating a list of numbers, and instead just provides an iterator object.

In Python 3, xrange() was renamed to range() - if you want a list, you have to specifically request it via list(range(n)).

Get environment variable value in Dockerfile

add -e key for passing environment variables to container. example:

$ MYSQLHOSTIP=$(sudo docker inspect -format="{{ .NetworkSettings.IPAddress }}" $MYSQL_CONRAINER_ID)
$ sudo docker run -e DBIP=$MYSQLHOSTIP -i -t myimage /bin/bash

root@87f235949a13:/# echo $DBIP
172.17.0.2

Cannot find vcvarsall.bat when running a Python script

Here's a simple solution. I'm using Python 2.7 and Windows 7.

What you're trying to install requires a C/C++ compiler but Python isn't finding it. A lot of Python packages are actually written in C/C++ and need to be compiled. vcvarsall.bat is needed to compile C++ and pip is assuming your machine can do that.

  1. Try upgrading setuptools first, because v6.0 and above will automatically detect a compiler. You might already have a compiler but Python can't find it. Open up a command line and type:

    pip install --upgrade setuptools

  2. Now try and install your package again:

    pip install [yourpackagename]

  3. If that didn't work, then it's certain you don't have a compiler, so you'll need to install one:
    http://www.microsoft.com/en-us/download/details.aspx?id=44266

  4. Now try again:

    pip install [yourpackagename]

And there you go. It should work for you.

Full Screen DialogFragment in Android

Try switching to a LinearLayout instead of RelativeLayout. I was targeting the 3.0 Honeycomb api when testing.

public class FragmentDialog extends Activity {

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

    Button button = (Button) findViewById(R.id.show);
    button.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            showDialog();
        }
    });
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
}

void showDialog() {
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    DialogFragment newFragment = MyDialogFragment.newInstance();
    newFragment.show(ft, "dialog");
}

public static class MyDialogFragment extends DialogFragment {

    static MyDialogFragment newInstance() {
        MyDialogFragment f = new MyDialogFragment();
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_dialog, container, false);
        return v;
    }

}
}

and the layouts: fragment_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:minWidth="1000dp"  
    android:minHeight="1000dp"> 
 </LinearLayout> 

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"
    android:background="#ffffff">
    <Button android:id="@+id/show"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="show">
    </Button>
</LinearLayout>

How to add a second css class with a conditional value in razor MVC 4

You can use String.Format function to add second class based on condition:

<div class="@String.Format("details {0}", Details.Count > 0 ? "show" : "hide")">

Sorting a DropDownList? - C#, ASP.NET

A C# solution for .NET 3.5 (needs System.Linq and System.Web.UI):

    public static void ReorderAlphabetized(this DropDownList ddl)
    {
        List<ListItem> listCopy = new List<ListItem>();
        foreach (ListItem item in ddl.Items)
            listCopy.Add(item);
        ddl.Items.Clear();
        foreach (ListItem item in listCopy.OrderBy(item => item.Text))
            ddl.Items.Add(item);
    }

Call it after you've bound your dropdownlist, e.g. OnPreRender:

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        ddlMyDropDown.ReorderAlphabetized();
    }

Stick it in your utility library for easy re-use.

Importing CSV File to Google Maps

none of that needed.... just go to:

http://www.gpsvisualizer.com/

now and load your csv file as-is. extra columns and all. it will slice and dice and use just the log & lat columns and plot it for you on google maps.

Need to ZIP an entire directory using Node.js

Archive.bulk is now deprecated, the new method to be used for this is glob:

var fileName =   'zipOutput.zip'
var fileOutput = fs.createWriteStream(fileName);

fileOutput.on('close', function () {
    console.log(archive.pointer() + ' total bytes');
    console.log('archiver has been finalized and the output file descriptor has closed.');
});

archive.pipe(fileOutput);
archive.glob("../dist/**/*"); //some glob pattern here
archive.glob("../dist/.htaccess"); //another glob pattern
// add as many as you like
archive.on('error', function(err){
    throw err;
});
archive.finalize();

How do I use Apache tomcat 7 built in Host Manager gui?

Just a note that all the above may not work for you with tomcat7 unless you've also done this:

sudo apt-get install tomcat7-admin

How to get the GL library/headers?

Windows

On Windows you need to include the gl.h header for OpenGL 1.1 support and link against OpenGL32.lib. Both are a part of the Windows SDK. In addition, you might want the following headers which you can get from http://www.opengl.org/registry .

  • <GL/glext.h> - OpenGL 1.2 and above compatibility profile and extension interfaces..
  • <GL/glcorearb.h> - OpenGL core profile and ARB extension interfaces, as described in appendix G.2 of the OpenGL 4.3 Specification. Does not include interfaces found only in the compatibility profile.
  • <GL/glxext.h> - GLX 1.3 and above API and GLX extension interfaces.
  • <GL/wglext.h> - WGL extension interfaces.

Linux

On Linux you need to link against libGL.so, which is usually a symlink to libGL.so.1, which is yet a symlink to the actual library/driver which is a part of your graphics driver. For example, on my system the actual driver library is named libGL.so.256.53, which is the version number of the nvidia driver I use. You also need to include the gl.h header, which is usually a part of a Mesa or Xorg package. Again, you might need glext.h and glxext.h from http://www.opengl.org/registry . glxext.h holds GLX extensions, the equivalent to wglext.h on Windows.

If you want to use OpenGL 3.x or OpenGL 4.x functionality without the functionality which were moved into the GL_ARB_compatibility extension, use the new gl3.h header from the registry webpage. It replaces gl.h and also glext.h (as long as you only need core functionality).

Last but not the least, glaux.h is not a header associated with OpenGL. I assume you've read the awful NEHE tutorials and just went along with it. Glaux is a horribly outdated Win32 library (1996) for loading uncompressed bitmaps. Use something better, like libPNG, which also supports alpha channels.

Android ImageButton with a selected state?

Create an XML-file in a res/drawable folder. For instance, "btn_image.xml":

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/bg_state_1"
          android:state_pressed="true"
          android:state_selected="true"/>
    <item android:drawable="@drawable/bg_state_2"
          android:state_pressed="true"
          android:state_selected="false"/>
    <item android:drawable="@drawable/bg_state_selected"
          android:state_selected="true"/>
    <item android:drawable="@drawable/bg_state_deselected"/>
</selector>

You can combine those files you like, for instance, change "bg_state_1" to "bg_state_deselected" and "bg_state_2" to "bg_state_selected".

In any of those files you can write something like:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <solid android:color="#ccdd00"/>
    <corners android:radius="5dp"/>
</shape>

Create in a layout file an ImageView or ImageButton with the following attributes:

<ImageView
    android:id="@+id/image"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:adjustViewBounds="true"
    android:background="@drawable/btn_image"
    android:padding="10dp"
    android:scaleType="fitCenter"
    android:src="@drawable/star"/>

Later in code:

image.setSelected(!image.isSelected());

Endless loop in C/C++

Well, there is a lot of taste in this one. I think people from a C background are more likely to prefer for(;;), which reads as "forever". If its for work, do what the locals do, if its for yourself, do the one that you can most easily read.

But in my experience, do { } while (1); is almost never used.

Load dimension value from res/values/dimension.xml from source code

Use a Kotlin Extension

You can add an extension to simplify this process. It enables you to just call context.dp(R.dimen. tutorial_cross_marginTop) to get the Float value

fun Context.px(@DimenRes dimen: Int): Int = resources.getDimension(dimen).toInt()

fun Context.dp(@DimenRes dimen: Int): Float = px(dimen) / resources.displayMetrics.density

If you want to handle it without context, you can use Resources.getSystem():

val Int.dp get() = this / Resources.getSystem().displayMetrics.density // Float

val Int.px get() = (this * Resources.getSystem().displayMetrics.density).toInt()

For example, on an xhdpi device, use 24.dp to get 12.0 or 12.px to get 24

PHP Fatal Error Failed opening required File

You could fix it with the PHP constant __DIR__

require_once __DIR__ . '/common/configs/config_templates.inc.php';

It is the directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname __FILE__ . This directory name does not have a trailing slash unless it is the root directory. 1

How to read a specific line using the specific line number from a file in Java?

Although as said in other answers, it is not possible to get to the exact line without knowing the offset ( pointer ) before. So, I've achieved this by creating an temporary index file which would store the offset values of every line. If the file is small enough, you could just store the indexes ( offset ) in memory without needing a separate file for it.

The offsets can be calculated by using the RandomAccessFile

    RandomAccessFile raf = new RandomAccessFile("myFile.txt","r"); 
    //above 'r' means open in read only mode
    ArrayList<Integer> arrayList = new ArrayList<Integer>();
    String cur_line = "";
    while((cur_line=raf.readLine())!=null)
    {
    arrayList.add(raf.getFilePointer());
    }
    //Print the 32 line
    //Seeks the file to the particular location from where our '32' line starts
    raf.seek(raf.seek(arrayList.get(31));
    System.out.println(raf.readLine());
    raf.close();

Also visit the java docs for more information: https://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html#mode

Complexity : This is O(n) as it reads the entire file once. Please be aware for the memory requirements. If it's too big to be in memory, then make a temporary file that stores the offsets instead of ArrayList as shown above.

Note : If all you want in '32' line, you just have to call the readLine() also available through other classes '32' times. The above approach is useful if you want to get the a specific line (based on line number of course) multiple times.

Thanks !

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

Use This This Will work For sure

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class ProtectedConfigFile {

    private static final char[] PASSWORD = "enfldsgbnlsngdlksdsgm".toCharArray();
    private static final byte[] SALT = { (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12, (byte) 0xde, (byte) 0x33,
            (byte) 0x10, (byte) 0x12, };

    public static void main(String[] args) throws Exception {
        String originalPassword = "Aman";
        System.out.println("Original password: " + originalPassword);
        String encryptedPassword = encrypt(originalPassword);
        System.out.println("Encrypted password: " + encryptedPassword);
        String decryptedPassword = decrypt(encryptedPassword);
        System.out.println("Decrypted password: " + decryptedPassword);
    }

    private static String encrypt(String property) throws GeneralSecurityException, UnsupportedEncodingException {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
        return base64Encode(pbeCipher.doFinal(property.getBytes("UTF-8")));
    }

    private static String base64Encode(byte[] bytes) {
        // NB: This class is internal, and you probably should use another impl
        return new BASE64Encoder().encode(bytes);
    }

    private static String decrypt(String property) throws GeneralSecurityException, IOException {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
        return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
    }

    private static byte[] base64Decode(String property) throws IOException {
        // NB: This class is internal, and you probably should use another impl
        return new BASE64Decoder().decodeBuffer(property);
    }

}

is of a type that is invalid for use as a key column in an index

The only solution is to use less data in your Unique Index. Your key can be NVARCHAR(450) at most.

"SQL Server retains the 900-byte limit for the maximum total size of all index key columns."

Read more at MSDN

How would I get a cron job to run every 30 minutes?

You mention you are using OS X- I have used cronnix in the past. It's not as geeky as editing it yourself, but it helped me learn what the columns are in a jiffy. Just a thought.

How to Troubleshoot Intermittent SQL Timeout Errors

I had an issue similar to this and found out is was due to a default .Net framework setting

Sqlcommand.Timeout

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.commandtimeout(v=VS.100).aspx

The default is 30 seconds as sated in the above url by Microsoft, try setting this to a higher number of seconds or maybe -1 before opening the connection to see if this solves the issue.

It maybe a setting in your web.config or app.config files or on you applicaiton / web server config files.

Find stored procedure by name

For SQL Server version 9.0 (2005), you can use the code below:

select * 
from 
syscomments c
inner join sys.procedures p on p.object_id = c.id
where 
p.name like '%usp_ConnectionsCount%';

Shuffling a list of objects

It works fine. I am trying it here with functions as list objects:

    from random import shuffle

    def foo1():
        print "foo1",

    def foo2():
        print "foo2",

    def foo3():
        print "foo3",

    A=[foo1,foo2,foo3]

    for x in A:
        x()

    print "\r"

    shuffle(A)
    for y in A:
        y()

It prints out: foo1 foo2 foo3 foo2 foo3 foo1 (the foos in the last row have a random order)

How to define a connection string to a SQL Server 2008 database?

Instead of writing it in your code directly I suggest you make use of the dedicated <connectionStrings> element in the .config file and retrieve it from there.

Also make use of the using statement so that after usage your connection automatically gets closed and disposed of.

A great reference for finding connection strings: connectionstrings.com/sql-server-2008.

How do I check if a directory exists? "is_dir", "file_exists" or both?

Second variant in question post is not ok, because, if you already have file with the same name, but it is not a directory, !file_exists($dir) will return false, folder will not be created, so error "failed to open stream: No such file or directory" will be occured. In Windows there is a difference between 'file' and 'folder' types, so need to use file_exists() and is_dir() at the same time, for ex.:

if (file_exists('file')) {
    if (!is_dir('file')) { //if file is already present, but it's not a dir
        //do something with file - delete, rename, etc.
        unlink('file'); //for example
        mkdir('file', NEEDED_ACCESS_LEVEL);
    }
} else { //no file exists with this name
    mkdir('file', NEEDED_ACCESS_LEVEL);
}

Error ITMS-90717: "Invalid App Store Icon"

Invalid App Store Icon. The App Store Icon in the asset catalog in 'YourApp.app' can't be transparent nor contain an alpha channel.

Solved in Catalina

  1. copy to desktop
  2. open image in PREVIEW APP.
  3. File -> Duplicate Close the first opened preview
  4. after try to close the second duplicated image, then it will prompt to save there you will available to untick AlPHA

look into my screenshot

nvalid App Store Icon Solved in Catalina

How to create a DataFrame of random integers with Pandas?

The recommended way to create random integers with NumPy these days is to use numpy.random.Generator.integers. (documentation)

import numpy as np
import pandas as pd

rng = np.random.default_rng()
df = pd.DataFrame(rng.integers(0, 100, size=(100, 4)), columns=list('ABCD'))
df
----------------------
      A    B    C    D
 0   58   96   82   24
 1   21    3   35   36
 2   67   79   22   78
 3   81   65   77   94
 4   73    6   70   96
... ...  ...  ...  ...
95   76   32   28   51
96   33   68   54   77
97   76   43   57   43
98   34   64   12   57
99   81   77   32   50
100 rows × 4 columns

How to find if a given key exists in a C++ std::map

Be careful in comparing the find result with the the end like for map 'm' as all answer have done above map::iterator i = m.find("f");

 if (i == m.end())
 {
 }
 else
 {
 }  

you should not try and perform any operation such as printing the key or value with iterator i if its equal to m.end() else it will lead to segmentation fault.

How do I use su to execute the rest of the bash script as that user?

This worked for me

I split out my "provisioning" from my "startup".

 # Configure everything else ready to run 
  config.vm.provision :shell, path: "provision.sh"
  config.vm.provision :shell, path: "start_env.sh", run: "always"

then in my start_env.sh

#!/usr/bin/env bash

echo "Starting Server Env"
#java -jar /usr/lib/node_modules/selenium-server-standalone-jar/jar/selenium-server-standalone-2.40.0.jar  &
#(cd /vagrant_projects/myproj && sudo -u vagrant -H sh -c "nohup npm install 0<&- &>/dev/null &;bower install 0<&- &>/dev/null &")
cd /vagrant_projects/myproj
nohup grunt connect:server:keepalive 0<&- &>/dev/null &
nohup apimocker -c /vagrant_projects/myproj/mock_api_data/config.json 0<&- &>/dev/null &

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

There's one big difference between CLOCK_REALTIME and MONOTONIC. CLOCK_REALTIME can jump forward or backward according to NTP. By default, NTP allows the clock rate to be speeded up or slowed down by up to 0.05%, but NTP cannot cause the monotonic clock to jump forward or backward.

How do you get a list of the names of all files present in a directory in Node.js?

Here's an asynchronous recursive version.

    function ( path, callback){
     // the callback gets ( err, files) where files is an array of file names
     if( typeof callback !== 'function' ) return
     var
      result = []
      , files = [ path.replace( /\/\s*$/, '' ) ]
     function traverseFiles (){
      if( files.length ) {
       var name = files.shift()
       fs.stat(name, function( err, stats){
        if( err ){
         if( err.errno == 34 ) traverseFiles()
    // in case there's broken symbolic links or a bad path
    // skip file instead of sending error
         else callback(err)
        }
        else if ( stats.isDirectory() ) fs.readdir( name, function( err, files2 ){
         if( err ) callback(err)
         else {
          files = files2
           .map( function( file ){ return name + '/' + file } )
           .concat( files )
          traverseFiles()
         }
        })
        else{
         result.push(name)
         traverseFiles()
        }
       })
      }
      else callback( null, result )
     }
     traverseFiles()
    }

Is there a difference between "throw" and "throw ex"?

It's better to use throw instead of throw ex.

throw ex reset the original stack trace and can't be found the previous stack trace.

If we use throw, we will get a full stack trace.

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

Either decorate your root entity with the XmlRoot attribute which will be used at compile time.

[XmlRoot(Namespace = "www.contoso.com", ElementName = "MyGroupName", DataType = "string", IsNullable=true)]

Or specify the root attribute when de serializing at runtime.

XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "user";
// xRoot.Namespace = "http://www.cpandl.com";
xRoot.IsNullable = true;

XmlSerializer xs = new XmlSerializer(typeof(User),xRoot);

How can I find script's directory?

import os
script_dir = os.path.dirname(os.path.realpath(__file__)) + os.sep

How can I find which tables reference a given table in Oracle SQL Developer?

This has been in the product for years - although it wasn't in the product in 2011.

But, simply click on the Model page.

Make sure you are on at least version 4.0 (released in 2013) to access this feature.

enter image description here

Remote Connections Mysql Ubuntu

To expose MySQL to anything other than localhost you will have to have the following line

For mysql version 5.6 and below

uncommented in /etc/mysql/my.cnf and assigned to your computers IP address and not loopback

For mysql version 5.7 and above

uncommented in /etc/mysql/mysql.conf.d/mysqld.cnf and assigned to your computers IP address and not loopback

#Replace xxx with your IP Address 
bind-address        = xxx.xxx.xxx.xxx

Or add a bind-address = 0.0.0.0 if you don't want to specify the IP

Then stop and restart MySQL with the new my.cnf entry. Once running go to the terminal and enter the following command.

lsof -i -P | grep :3306

That should come back something like this with your actual IP in the xxx's

mysqld  1046  mysql  10u  IPv4  5203  0t0  TCP  xxx.xxx.xxx.xxx:3306 (LISTEN)

If the above statement returns correctly you will then be able to accept remote users. However for a remote user to connect with the correct priveleges you need to have that user created in both the localhost and '%' as in.

CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';

then,

GRANT ALL ON *.* TO 'myuser'@'localhost';
GRANT ALL ON *.* TO 'myuser'@'%';

and finally,

FLUSH PRIVILEGES; 
EXIT;

If you don't have the same user created as above, when you logon locally you may inherit base localhost privileges and have access issues. If you want to restrict the access myuser has then you would need to read up on the GRANT statement syntax HERE If you get through all this and still have issues post some additional error output and the my.cnf appropriate lines.

NOTE: If lsof does not return or is not found you can install it HERE based on your Linux distribution. You do not need lsof to make things work, but it is extremely handy when things are not working as expected.

UPDATE: If even after adding/changing the bind-address in my.cnf did not work, then go and change it in the place it was originally declared:

/etc/mysql/mariadb.conf.d/50-server.cnf

Does SVG support embedding of bitmap images?

It is also possible to include bitmaps. I think you also can use transformations on that.

Ways to eliminate switch in code

In JavaScript using Associative array:
this:

function getItemPricing(customer, item) {
    switch (customer.type) {
        // VIPs are awesome. Give them 50% off.
        case 'VIP':
            return item.price * item.quantity * 0.50;

            // Preferred customers are no VIPs, but they still get 25% off.
        case 'Preferred':
            return item.price * item.quantity * 0.75;

            // No discount for other customers.
        case 'Regular':
        case
        default:
            return item.price * item.quantity;
    }
}

becomes this:

function getItemPricing(customer, item) {
var pricing = {
    'VIP': function(item) {
        return item.price * item.quantity * 0.50;
    },
    'Preferred': function(item) {
        if (item.price <= 100.0)
            return item.price * item.quantity * 0.75;

        // Else
        return item.price * item.quantity;
    },
    'Regular': function(item) {
        return item.price * item.quantity;
    }
};

    if (pricing[customer.type])
        return pricing[customer.type](item);
    else
        return pricing.Regular(item);
}

Courtesy