Programs & Examples On #Freepascal

Free Pascal is a multi-dialect, multi-platform Object Pascal compiler. Originally started to replace the retired Turbo Pascal compiler, it now attempts to follow the Delphi dialect still being developed by Embarcadero Technologies. It has compiler modes for Delphi, Turbo Pascal and Mac Pascal. It also has two modes for it's own superset dialect. One with exceptions, classes and interfaces, and one without.

Facebook page automatic "like" URL (for QR Code)

In my opinion, it is not possible for the like button (and I hope it is not possible).

But, you can trigger a custom OpenGraph v2 action, or display a like button linked to your facebook page.

Parsing time string in Python

Here's a stdlib solution that supports a variable utc offset in the input time string:

>>> from email.utils import parsedate_tz, mktime_tz
>>> from datetime import datetime, timedelta
>>> timestamp = mktime_tz(parsedate_tz('Tue May 08 15:14:45 +0800 2012'))
>>> utc_time = datetime(1970, 1, 1) + timedelta(seconds=timestamp)
>>> utc_time
datetime.datetime(2012, 5, 8, 7, 14, 45)

How to set a cron job to run every 3 hours

Change Minute parameter to 0.

You can set the cron for every three hours as:

0 */3 * * * your command here ..

Android: how to convert whole ImageView to Bitmap?

Have you tried:

BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();

How to access accelerometer/gyroscope data from Javascript?

Usefull fallback here: https://developer.mozilla.org/en-US/docs/Web/Events/MozOrientation

function orientationhandler(evt){


  // For FF3.6+
  if (!evt.gamma && !evt.beta) {
    evt.gamma = -(evt.x * (180 / Math.PI));
    evt.beta = -(evt.y * (180 / Math.PI));
  }

  // use evt.gamma, evt.beta, and evt.alpha 
  // according to dev.w3.org/geo/api/spec-source-orientation


}

window.addEventListener('deviceorientation',  orientationhandler, false);
window.addEventListener('MozOrientation',     orientationhandler, false);

Update a table using JOIN in SQL Server?

Aaron's approach above worked perfectly for me. My update statement was slightly different because I needed to join based on two fields concatenated in one table to match a field in another table.

 --update clients table cell field from custom table containing mobile numbers

update clients
set cell = m.Phone
from clients as c
inner join [dbo].[COSStaffMobileNumbers] as m 
on c.Last_Name + c.First_Name = m.Name

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

Instantly detect client disconnection from server socket

Someone mentioned keepAlive capability of TCP Socket. Here it is nicely described:

http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html

I'm using it this way: after the socket is connected, I'm calling this function, which sets keepAlive on. The keepAliveTime parameter specifies the timeout, in milliseconds, with no activity until the first keep-alive packet is sent. The keepAliveInterval parameter specifies the interval, in milliseconds, between when successive keep-alive packets are sent if no acknowledgement is received.

    void SetKeepAlive(bool on, uint keepAliveTime, uint keepAliveInterval)
    {
        int size = Marshal.SizeOf(new uint());

        var inOptionValues = new byte[size * 3];

        BitConverter.GetBytes((uint)(on ? 1 : 0)).CopyTo(inOptionValues, 0);
        BitConverter.GetBytes((uint)keepAliveTime).CopyTo(inOptionValues, size);
        BitConverter.GetBytes((uint)keepAliveInterval).CopyTo(inOptionValues, size * 2);

        socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
    }

I'm also using asynchronous reading:

socket.BeginReceive(packet.dataBuffer, 0, 128,
                    SocketFlags.None, new AsyncCallback(OnDataReceived), packet);

And in callback, here is caught timeout SocketException, which raises when socket doesn't get ACK signal after keep-alive packet.

public void OnDataReceived(IAsyncResult asyn)
{
    try
    {
        SocketPacket theSockId = (SocketPacket)asyn.AsyncState;

        int iRx = socket.EndReceive(asyn);
    }
    catch (SocketException ex)
    {
        SocketExceptionCaught(ex);
    }
}

This way, I'm able to safely detect disconnection between TCP client and server.

How to serve an image using nodejs

You should use the express framework.

npm install express

and then

var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(8080);

and then the URL localhost:8080/images/logo.gif should work.

Fail during installation of Pillow (Python module) in Linux

On Raspberry pi II, I had the same problem. After trying the following, I solved the problem. The solution is:

sudo apt-get update
sudo apt-get install libjpeg-dev

R Error in x$ed : $ operator is invalid for atomic vectors

Here x is a vector. You need to convert it into a dataframe for using $ operator.

 x <- as.data.frame(x) 

will work for you.

x<-c(1,2)
names(x)<- c("bob","ed")
x <- as.data.frame(x)

will give you output of x as:
bob 1
ed 2
And, will give you output of x$ed as:
NULL
If you want bob and ed as column names then you need to transpose the dataframe like x <- as.data.frame(t(x)) So your code becomes

x<-c(1,2)
x
names(x)<- c("bob","ed")
x$ed
x <- as.data.frame(t(x))

Now the output of x$ed is:
[1] 2

How to get "their" changes in the middle of conflicting Git rebase?

You want to use:

git checkout --ours foo/bar.java
git add foo/bar.java

If you rebase a branch feature_x against main (i.e. running git rebase main while on branch feature_x), during rebasing ours refers to main and theirs to feature_x.

As pointed out in the git-rebase docs:

Note that a rebase merge works by replaying each commit from the working branch on top of the branch. Because of this, when a merge conflict happens, the side reported as ours is the so-far rebased series, starting with <upstream>, and theirs is the working branch. In other words, the sides are swapped.

For further details read this thread.

How do I display image in Alert/confirm box in Javascript?

Short answer: You can't.

Long answer: You could use a modal to display a popup with the image you need.

You can refer to this as an example to a modal.

Is Python faster and lighter than C++?

The problem here is that you have two different languages that solve two different problems... its like comparing C++ with assembler.

Python is for rapid application development and for when performance is a minimal concern.

C++ is not for rapid application development and inherits a legacy of speed from C - for low level programming.

Omitting the first line from any Linux command output

The tail program can do this:

ls -lart | tail -n +2

The -n +2 means “start passing through on the second line of output”.

Retrieve specific commit from a remote Git repository

You can simply fetch a single commit of a remote repo with

git fetch <repo> <commit>

where,

  • <repo> can be a remote repo name (e.g. origin) or even a remote repo URL (e.g. https://git.foo.com/myrepo.git)
  • <commit> can be the SHA1 commit

for example

git fetch https://git.foo.com/myrepo.git 0a071603d87e0b89738599c160583a19a6d95545

after you fetched the commit (and the missing ancestors) you can simply checkout it with

git checkout FETCH_HEAD

Note that this will bring you in the "detached head" state.

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

In case it helps anyone I will post what worked for me.

I had to plug my S3 into a direct USB port of my PC for it to prompt me to accept the RSA signature. I had my S3 plugged into a hub before then.

Now the S3 is detected when using both the direct USB port of the PC and via the hub.

NOTE - You may need to also run adb devices from the command line to get your S3 to re-request permission.

D:\apps\android-sdk-windows\platform-tools>adb devices
List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
9283759342847566        unauthorized

...accept signature on phone...

D:\apps\android-sdk-windows\platform-tools>adb devices
List of devices attached
9283759342847566        device

What version of Python is on my Mac?

If you have both Python2 and Python3 installed on your Mac, you can use

python --version

to check the version of Python2, and

python3 --version

to check the version of Python3.

However, if only Python3 is installed, then your system might use python instead of python3 for Python3. In this case, you can just use

python --version

to check the version of Python3.

Best way to iterate through a Perl array

The best way to decide questions like this to benchmark them:

use strict;
use warnings;
use Benchmark qw(:all);

our @input_array = (0..1000);

my $a = sub {
    my @array = @{[ @input_array ]};
    my $index = 0;
    foreach my $element (@array) {
       die unless $index == $element;
       $index++;
    }
};

my $b = sub {
    my @array = @{[ @input_array ]};
    my $index = 0;
    while (defined(my $element = shift @array)) {
       die unless $index == $element;
       $index++;
    }
};

my $c = sub {
    my @array = @{[ @input_array ]};
    my $index = 0;
    while (scalar(@array) !=0) {
       my $element = shift(@array);
       die unless $index == $element;
       $index++;
    }
};

my $d = sub {
    my @array = @{[ @input_array ]};
    foreach my $index (0.. $#array) {
       my $element = $array[$index];
       die unless $index == $element;
    }
};

my $e = sub {
    my @array = @{[ @input_array ]};
    for (my $index = 0; $index <= $#array; $index++) {
       my $element = $array[$index];
       die unless $index == $element;
    }
};

my $f = sub {
    my @array = @{[ @input_array ]};
    while (my ($index, $element) = each @array) {
       die unless $index == $element;
    }
};

my $count;
timethese($count, {
   '1' => $a,
   '2' => $b,
   '3' => $c,
   '4' => $d,
   '5' => $e,
   '6' => $f,
});

And running this on perl 5, version 24, subversion 1 (v5.24.1) built for x86_64-linux-gnu-thread-multi

I get:

Benchmark: running 1, 2, 3, 4, 5, 6 for at least 3 CPU seconds...
         1:  3 wallclock secs ( 3.16 usr +  0.00 sys =  3.16 CPU) @ 12560.13/s (n=39690)
         2:  3 wallclock secs ( 3.18 usr +  0.00 sys =  3.18 CPU) @ 7828.30/s (n=24894)
         3:  3 wallclock secs ( 3.23 usr +  0.00 sys =  3.23 CPU) @ 6763.47/s (n=21846)
         4:  4 wallclock secs ( 3.15 usr +  0.00 sys =  3.15 CPU) @ 9596.83/s (n=30230)
         5:  4 wallclock secs ( 3.20 usr +  0.00 sys =  3.20 CPU) @ 6826.88/s (n=21846)
         6:  3 wallclock secs ( 3.12 usr +  0.00 sys =  3.12 CPU) @ 5653.53/s (n=17639)

So the 'foreach (@Array)' is about twice as fast as the others. All the others are very similar.

@ikegami also points out that there are quite a few differences in these implimentations other than speed.

Check if Nullable Guid is empty in c#

Check Nullable<T>.HasValue

if(!SomeProperty.HasValue ||SomeProperty.Value == Guid.Empty)
{
 //not valid GUID
}
else
{
 //Valid GUID
}

Read text file into string. C++ ifstream

To read a whole line from a file into a string, use std::getline like so:

 std::ifstream file("my_file");
 std::string temp;
 std::getline(file, temp);

You can do this in a loop to until the end of the file like so:

 std::ifstream file("my_file");
 std::string temp;
 while(std::getline(file, temp)) {
      //Do with temp
 }

References

http://en.cppreference.com/w/cpp/string/basic_string/getline

http://en.cppreference.com/w/cpp/string/basic_string

How to upload file to server with HTTP POST multipart/form-data?

The below code reads a file, converts it to a byte array and then makes a request to the server.

    public void PostImage()
    {
        HttpClient httpClient = new HttpClient();
        MultipartFormDataContent form = new MultipartFormDataContent();

        byte[] imagebytearraystring = ImageFileToByteArray(@"C:\Users\Downloads\icon.png");
        form.Add(new ByteArrayContent(imagebytearraystring, 0, imagebytearraystring.Count()), "profile_pic", "hello1.jpg");
        HttpResponseMessage response = httpClient.PostAsync("your url", form).Result;

        httpClient.Dispose();
        string sd = response.Content.ReadAsStringAsync().Result;
    }

    private byte[] ImageFileToByteArray(string fullFilePath)
    {
        FileStream fs = File.OpenRead(fullFilePath);
        byte[] bytes = new byte[fs.Length];
        fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
        fs.Close();
        return bytes;
    }

Bash script to run php script

I'm pretty sure something like this is what you are looking for:

#!/bin/sh

php /pathToScript/script.php

Save that with your desired script name (such as runPHP.sh) and give it execution rights, then you can use it however you want.

Edit: You might as well not use a bash script at all and just add the "php ..." command to the crontab, if I'm not mistaken.

Good luck!

How to update a value in a json file and save it through node.js

Save data after task completion

fs.readFile("./sample.json", 'utf8', function readFileCallback(err, data) {
        if (err) {
          console.log(err);
        } else {
          fs.writeFile("./sample.json", JSON.stringify(result), 'utf8', err => {
            if (err) throw err;
            console.log('File has been saved!');
          });
        }
      });

HTML for the Pause symbol in audio and video control

I'm using ▐ ▌

HTML: &#9616;&nbsp;&#9612;

CSS: \2590\A0\258C

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

Check that the "Windows Management Instrumentation (WMI-In)" rule is enabled in the firewall for each remote machine.

Or in an Administrative Command/Powershell prompt run:

netsh advfirewall firewall set rule group="Windows Management Instrumentation (WMI)" new enable=yes

Get second child using jQuery

Try this:

$("td:eq(1)", $(t))

or

$("td", $(t)).eq(1)

Entity Framework - Generating Classes

  1. Open the EDMX model
  2. Right click -> Update Model from Browser -> Stored Procedure -> Select your stored procedure -> Finish
  3. See the Model Browser popping up next to Solution Explorer.
  4. Go to Function Imports -> Right click on your Stored Procedure -> Add Function Import
  5. Select the Entities under Return a Collection of -> Select your Entity name from the drop down
  6. Build your Solution.

Take a list of numbers and return the average

If you have the numpy package:

In [16]: x = [1,2,3,4]    
    ...: import numpy
    ...: numpy.average(x)

Out[16]: 2.5

What's the difference between Cache-Control: max-age=0 and no-cache?

max-age=0

This is equivalent to clicking Refresh, which means, give me the latest copy unless I already have the latest copy.

no-cache

This is holding Shift while clicking Refresh, which means, just redo everything no matter what.

Validating with an XML schema in Python

There are two ways(actually there are more) that you could do this.
1. using lxml
pip install lxml

from lxml import etree, objectify
from lxml.etree import XMLSyntaxError

def xml_validator(some_xml_string, xsd_file='/path/to/my_schema_file.xsd'):
    try:
        schema = etree.XMLSchema(file=xsd_file)
        parser = objectify.makeparser(schema=schema)
        objectify.fromstring(some_xml_string, parser)
        print "YEAH!, my xml file has validated"
    except XMLSyntaxError:
        #handle exception here
        print "Oh NO!, my xml file does not validate"
        pass

xml_file = open('my_xml_file.xml', 'r')
xml_string = xml_file.read()
xml_file.close()

xml_validator(xml_string, '/path/to/my_schema_file.xsd')
  1. Use xmllint from the commandline. xmllint comes installed in many linux distributions.

>> xmllint --format --pretty 1 --load-trace --debug --schema /path/to/my_schema_file.xsd /path/to/my_xml_file.xml

CSS Transition doesn't work with top, bottom, left, right

Something that is not relevant for the OP, but maybe for someone else in the future:

For pixels (px), if the value is "0", the unit can be omitted: right: 0 and right: 0px both work.

However I noticed that in Firefox and Chrome this is not the case for the seconds unit (s). While transition: right 1s ease 0s works, transition: right 1s ease 0 (missing unit s for last value transition-delay) does not (it does work in Edge however).

In the following example, you'll see that right works for both 0px and 0, but transition only works for 0s and it doesn't work with 0.

_x000D_
_x000D_
#box {_x000D_
    border: 1px solid black;_x000D_
    height: 240px;_x000D_
    width: 260px;_x000D_
    margin: 50px;_x000D_
    position: relative;_x000D_
}_x000D_
.jump {_x000D_
    position: absolute;_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    color: white;_x000D_
    padding: 5px;_x000D_
}_x000D_
#jump1 {_x000D_
    background-color: maroon;_x000D_
    top: 0px;_x000D_
    right: 0px;_x000D_
    transition: right 1s ease 0s;_x000D_
}_x000D_
#jump2 {_x000D_
    background-color: green;_x000D_
    top: 60px;_x000D_
    right: 0;_x000D_
    transition: right 1s ease 0s;_x000D_
}_x000D_
#jump3 {_x000D_
    background-color: blue;_x000D_
    top: 120px;_x000D_
    right: 0px;_x000D_
    transition: right 1s ease 0;_x000D_
}_x000D_
#jump4 {_x000D_
    background-color: gray;_x000D_
    top: 180px;_x000D_
    right: 0;_x000D_
    transition: right 1s ease 0;_x000D_
}_x000D_
#box:hover .jump {_x000D_
    right: 50px;_x000D_
}
_x000D_
<div id="box">_x000D_
  <div class="jump" id="jump1">right: 0px<br>transition: right 1s ease 0s</div>_x000D_
  <div class="jump" id="jump2">right: 0<br>transition: right 1s ease 0s</div>_x000D_
  <div class="jump" id="jump3">right: 0px<br>transition: right 1s ease 0</div>_x000D_
  <div class="jump" id="jump4">right: 0<br>transition: right 1s ease 0</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Rails 3.1 and Image Assets

In 3.1 you just get rid of the 'images' part of the path. So an image that lives in /assets/images/example.png will actually be accessible in a get request at this url - /assets/example.png

Because the assets/images folder gets generated along with a new 3.1 app, this is the convention that they probably want you to follow. I think that's where image_tag will look for it, but I haven't tested that yet.

Also, during the RailsConf keynote, I remember D2h saying the the public folder should not have much in it anymore, mostly just error pages and a favicon.

Spring MVC: Error 400 The request sent by the client was syntactically incorrect

The @RequestParam String action suggests there is a parameter present within the request with the name action which is absent in your form. You must either:

  1. Submit a parameter named value e.g. <input name="action" />
  2. Set the required parameter to false within the @RequestParam e.g. @RequestParam(required=false)

@angular/material/index.d.ts' is not a module

@angular/material has changed its folder structure. Now you need to use all the modules from their respective folders instead of just material folder

For example:

import { MatDialogModule } from "@angular/material";

has now changed to

import { MatDialogModule } from "@angular/material/dialog";

You can check the following to find the correct path for your module

https://material.angular.io/components/categories

Just navigate to the API tab of required module and find the correct path like this 1

How to create a sticky footer that plays well with Bootstrap 3

The answer, as Schmalzy points out, can be found here in the examples section of the getbootstrap site.

But that example does not include a top nav. For fixed top nav with sticky footer, see this plnkr, or code below.

Style CSS:

/* Styles go here */

/* Sticky footer styles
-------------------------------------------------- */

html,
body {
  height: 100%;
  /* The html and body elements cannot have any padding or margin. */
}

/* Wrapper for page content to push down footer */
#wrap {
  min-height: 100%;
  height: auto;
  /* Negative indent footer by its height */
  margin: 0 auto -60px;
  /* Pad bottom by footer height */
  padding: 0 0 60px;
}

/* Set the fixed height of the footer here */
#footer {
  height: 60px;
  background-color: #f5f5f5;
}


/* Custom page CSS
-------------------------------------------------- */
/* Not required for template or sticky footer method. */

.container {
  width: auto;
  max-width: 680px;
  padding: 0 15px;
}
.container .credit {
  margin: 20px 0;
}

Index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="shortcut icon" href="../../docs-assets/ico/favicon.png">

    <title>Sticky Footer Template for Bootstrap</title>

    <!-- Bootstrap core CSS -->
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.1/css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="style.css" rel="stylesheet">

    <!-- Just for debugging purposes. Don't actually copy this line! -->
    <!--[if lt IE 9]><script src="../../docs-assets/js/ie8-responsive-file-warning.js"></script><![endif]-->

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
    <![endif]-->
  </head>

  <body>

    <!-- Wrap all page content here -->
    <div id="wrap">

<nav class="navbar navbar-default" role="navigation">
  <!-- Brand and toggle get grouped for better mobile display -->
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
  </div>

  <!-- Collect the nav links, forms, and other content for toggling -->
  <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Link</a></li>
      <li><a href="#">Link</a></li>
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li class="divider"></li>
          <li><a href="#">Separated link</a></li>
          <li class="divider"></li>
          <li><a href="#">One more separated link</a></li>
        </ul>
      </li>
    </ul>
    <form class="navbar-form navbar-left" role="search">
      <div class="form-group">
        <input type="text" class="form-control" placeholder="Search">
      </div>
      <button type="submit" class="btn btn-default">Submit</button>
    </form>
    <ul class="nav navbar-nav navbar-right">
      <li><a href="#">Link</a></li>
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li class="divider"></li>
          <li><a href="#">Separated link</a></li>
        </ul>
      </li>
    </ul>
  </div><!-- /.navbar-collapse -->
</nav>

      <!-- Begin page content -->
      <div class="container">

        <div class="page-header">
          <h1>Sticky footer</h1>
        </div>
        <p class="lead">Pin a fixed-height footer to the bottom of the viewport in desktop browsers with this custom HTML and CSS.</p>
        <p>Use <a href="../sticky-footer-navbar">the sticky footer with a fixed navbar</a> if need be, too.</p>
      </div>
    </div><!-- Wrap Div end -->

    <div id="footer">
      <div class="container">
        <p class="text-muted credit">Example courtesy <a href="http://martinbean.co.uk">Martin Bean</a> and <a href="http://ryanfait.com/sticky-footer/">Ryan Fait</a>.</p>
      </div>
    </div>


    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
  </body>
</html>

jQuery: how to find first visible input/select/textarea excluding buttons?

Here is my solution. The code should be easy enough to follow but here is the idea:

  • get all inputs, selects, and textareas
  • filter out all buttons and hidden fields
  • filter to only enabled, visible fields
  • select the first one
  • focus the selected field

The code:

function focusFirst(parent) {
    $(parent).find('input, textarea, select')
        .not('input[type=hidden],input[type=button],input[type=submit],input[type=reset],input[type=image],button')
        .filter(':enabled:visible:first')
        .focus();
}

Then simply call focusFirst with your parent element or selector.

Selector:

focusFirst('form#aspnetForm');

Element:

var el = $('form#aspnetForm');
focusFirst(el);

Import .bak file to a database in SQL server

Simply use

sp_restoredb 'Your Database Name' ,'Location From you want to restore'

Example: sp_restoredb 'omDB','D:\abc.bak'

How do you render primitives as wireframes in OpenGL?

If it's OpenGL ES 2.0 you're dealing with, you can choose one of draw mode constants from

GL_LINE_STRIP, GL_LINE_LOOP, GL_LINES, to draw lines,

GL_POINTS (if you need to draw only vertices), or

GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, and GL_TRIANGLES to draw filled triangles

as first argument to your

glDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid * indices)

or

glDrawArrays(GLenum mode, GLint first, GLsizei count) calls.

What is a reasonable length limit on person "Name" fields?

What you're really asking is a related, but substantially different question: how often do I want to truncate names in order to fit them in the database? The answer depends both on the frequency of different lengths of names as well as the maximum lengths chosen. This concern is balanced by the concerns about resources used by the database. Considering how little overhead difference there is between different max lengths for a varchar field I'd generally err on the side of never being forced to truncate a name and make the field as large as I dared.

What is the "hasClass" function with plain JavaScript?

I use a simple/minimal solution, one line, cross browser, and works with legacy browsers as well:

/\bmyClass/.test(document.body.className) // notice the \b command for whole word 'myClass'

This method is great because does not require polyfills and if you use them for classList it's much better in terms of performance. At least for me.

Update: I made a tiny polyfill that's an all round solution I use now:

function hasClass(element,testClass){
  if ('classList' in element) { return element.classList.contains(testClass);
} else { return new Regexp(testClass).exec(element.className); } // this is better

//} else { return el.className.indexOf(testClass) != -1; } // this is faster but requires indexOf() polyfill
  return false;
}

For the other class manipulation, see the complete file here.

How to print colored text to the terminal?

Stupidly simple, based on joeld's answer:

class PrintInColor:
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    LIGHT_PURPLE = '\033[94m'
    PURPLE = '\033[95m'
    END = '\033[0m'

    @classmethod
    def red(cls, s, **kwargs):
        print(cls.RED + s + cls.END, **kwargs)

    @classmethod
    def green(cls, s, **kwargs):
        print(cls.GREEN + s + cls.END, **kwargs)

    @classmethod
    def yellow(cls, s, **kwargs):
        print(cls.YELLOW + s + cls.END, **kwargs)

    @classmethod
    def lightPurple(cls, s, **kwargs):
        print(cls.LIGHT_PURPLE + s + cls.END, **kwargs)

    @classmethod
    def purple(cls, s, **kwargs):
        print(cls.PURPLE + s + cls.END, **kwargs)

Then just

PrintInColor.red('hello', end=' ')
PrintInColor.green('world')

Delaying AngularJS route change until model loaded to prevent flicker

One possible solution might be to use the ng-cloak directive with the element where we are using the models e.g.

<div ng-cloak="">
  Value in  myModel is: {{myModel}}
</div>

I think this one takes least effort.

how to use javascript Object.defineProperty

defineProperty is a method on Object which allow you to configure the properties to meet some criterias. Here is a simple example with an employee object with two properties firstName & lastName and append the two properties by overriding the toString method on the object.

var employee = {
    firstName: "Jameel",
    lastName: "Moideen"
};
employee.toString=function () {
    return this.firstName + " " + this.lastName;
};
console.log(employee.toString());

You will get Output as : Jameel Moideen

I am going to change the same code by using defineProperty on the object

var employee = {
    firstName: "Jameel",
    lastName: "Moideen"
};
Object.defineProperty(employee, 'toString', {
    value: function () {
        return this.firstName + " " + this.lastName;
    },
    writable: true,
    enumerable: true,
    configurable: true
});
console.log(employee.toString());

The first parameter is the name of the object and then second parameter is name of the property we are adding , in our case it’s toString and then the last parameter is json object which have a value going to be a function and three parameters writable,enumerable and configurable.Right now I just declared everything as true.

If u run the example you will get Output as : Jameel Moideen

Let’s understand why we need the three properties such as writable,enumerable and configurable.

writable

One of the very annoying part of the javascript is , if you change the toString property to something else for example

enter image description here

if you run this again , everything gets breaks. Let’s change writable to false. If run the same again you will get the correct output as ‘Jameel Moideen’ . This property will prevent overwrite this property later.

enumerable

if you print all the keys inside the object , you can see all the properties including toString.

console.log(Object.keys(employee));

enter image description here

if you set enumerable to false , you can hide toString property from everybody else. If run this again you will get firstName,lastName

configurable

if someone later redefined the object on later for example enumerable to true and run it. You can see toString property came again.

var employee = {
    firstName: "Jameel",
    lastName: "Moideen"
};
Object.defineProperty(employee, 'toString', {
    value: function () {
        return this.firstName + " " + this.lastName;
    },
    writable: false,
    enumerable: false,
    configurable: true
});

//change enumerable to false
Object.defineProperty(employee, 'toString', {

    enumerable: true
});
employee.toString="changed";
console.log(Object.keys(employee));

enter image description here

you can restrict this behavior by set configurable to false.

Orginal reference of this information is from my personal Blog

How do I make a text go onto the next line if it overflows?

As long as you specify a width on the element, it should wrap itself without needing anything else.

how to add script inside a php code?

<?php
  echo"<script language='javascript'>

</script>
";
?>

Find duplicate lines in a file and count how many time each line was duplicated?

To find duplicate counts use below command as requested by you :

sort filename | uniq -c | awk '{print $2, $1}'

Where Is Machine.Config?

You can run this in powershell: copy & paste in power shell [System.Runtime.InteropServices.RuntimeEnvironment]::SystemConfigurationFile

mine output is: C:\Windows\Microsoft.NET\Framework\v2.0.50527\config\machine.config

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

Using sed, Insert a line above or below the pattern?

To append after the pattern: (-i is for in place replace). line1 and line2 are the lines you want to append(or prepend)

sed -i '/pattern/a \
line1 \
line2' inputfile

Output:

#cat inputfile
 pattern
 line1 line2 

To prepend the lines before:

sed -i '/pattern/i \
line1 \
line2' inputfile

Output:

#cat inputfile
 line1 line2 
 pattern

getResourceAsStream returns null

Make sure your resource directory (e.g. "src") is in your classpath (make sure it's a source directory in your build path in eclipse).

Make sure clazz is loaded from the main classloader.

Then, to load src/initialization/Lifepaths.txt, use

clazz.getResourceAsStream("/initialization/Lifepaths.txt");

Why: clazz.getResourcesAsStream(foo) looks up foo from within the classpath of clazz, relative to the directory clazz lives in. The leading "/" makes it load from the root of any directory in the classpath of clazz.

Unless you're in a container of some kind, like Tomcat, or are doing something with ClassLoaders directly, you can just treat your eclipse/command line classpath as the only classloader classpath.

Open file in a relative location in Python

Python just passes the filename you give it to the operating system, which opens it. If your operating system supports relative paths like main/2091/data.txt (hint: it does), then that will work fine.

You may find that the easiest way to answer a question like this is to try it and see what happens.

How to get AM/PM from a datetime in PHP

for flexibility with different formats, use:

$dt = DateTime::createFromFormat('m/d/Y H:i:s', '08/04/2010 22:15:00');
echo $dt->format('g:i A')

Check the php manual for additional format options.

How to check a Long for null in java

You can check Long object for null value with longValue == null , you can use longValue == 0L for long (primitive), because default value of long is 0L, but it's result will be true if longValue is zero too

How do I calculate the date six months from the current date using the datetime Python module?

Modified Johannes Wei's answer in the case 1new_month = 121. This works perfectly for me. The months could be positive or negative.

def addMonth(d,months=1):
    year, month, day = d.timetuple()[:3]
    new_month = month + months
    return datetime.date(year + ((new_month-1) / 12), (new_month-1) % 12 +1, day)

JavaScript or jQuery browser back button click detector

In case of HTML5 this will do the trick

window.onpopstate = function() {
   alert("clicked back button");
}; history.pushState({}, '');

Show/Hide the console window of a C# console application

See my post here:

Show Console in Windows Application

You can make a Windows application (with or without the window) and show the console as desired. Using this method the console window never appears unless you explicitly show it. I use it for dual-mode applications that I want to run in either console or gui mode depending on how they are opened.

Parse (split) a string in C++ using string delimiter (standard C++)

You can also use regex for this:

std::vector<std::string> split(const std::string str, const std::string regex_str)
{
    std::regex regexz(regex_str);
    std::vector<std::string> list(std::sregex_token_iterator(str.begin(), str.end(), regexz, -1),
                                  std::sregex_token_iterator());
    return list;
}

which is equivalent to :

std::vector<std::string> split(const std::string str, const std::string regex_str)
{
    std::sregex_token_iterator token_iter(str.begin(), str.end(), regexz, -1);
    std::sregex_token_iterator end;
    std::vector<std::string> list;
    while (token_iter != end)
    {
        list.emplace_back(*token_iter++);
    }
    return list;
}

and use it like this :

#include <iostream>
#include <string>
#include <regex>

std::vector<std::string> split(const std::string str, const std::string regex_str)
{   // a yet more concise form!
    return { std::sregex_token_iterator(str.begin(), str.end(), std::regex(regex_str), -1), std::sregex_token_iterator() };
}

int main()
{
    std::string input_str = "lets split this";
    std::string regex_str = " "; 
    auto tokens = split(input_str, regex_str);
    for (auto& item: tokens)
    {
        std::cout<<item <<std::endl;
    }
}

play with it online! http://cpp.sh/9sumb

you can simply use substrings, characters, etc like normal, or use actual regular expressions to do the splitting.
its also concise and C++11!

If else in stored procedure sql server

If there are no matching row/s then @ParLngId will be NULL not zero, so you need IF @ParLngId IS NULL.

You should also use SCOPE_IDENTITY() rather than @@IDENTITY.

c++ exception : throwing std::string

Simplest way to throw an Exception in C++:

#include <iostream>
using namespace std;
void purturb(){
    throw "Cannot purturb at this time.";
}
int main() {
    try{
        purturb();
    }
    catch(const char* msg){
        cout << "We caught a message: " << msg << endl;
    }
    cout << "done";
    return 0;
}

This prints:

We caught a message: Cannot purturb at this time.
done

If you catch the thrown exception, the exception is contained and the program will ontinue. If you do not catch the exception, then the program exists and prints:

This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.

Automated testing for REST Api

I implemented many automation cases based on REST Assured , a jave DSL for testing restful service. https://code.google.com/p/rest-assured/

The syntax is easy, it supports json and xml. https://code.google.com/p/rest-assured/wiki/Usage

Before that, I tried SOAPUI and had some issues with the free version. Plus the cases are in xml files which hard to extend and reuse, simply I don't like

How do I replace whitespaces with underscore?

Replacing spaces is fine, but I might suggest going a little further to handle other URL-hostile characters like question marks, apostrophes, exclamation points, etc.

Also note that the general consensus among SEO experts is that dashes are preferred to underscores in URLs.

import re

def urlify(s):

    # Remove all non-word characters (everything except numbers and letters)
    s = re.sub(r"[^\w\s]", '', s)

    # Replace all runs of whitespace with a single dash
    s = re.sub(r"\s+", '-', s)

    return s

# Prints: I-cant-get-no-satisfaction"
print(urlify("I can't get no satisfaction!"))

Is there a way to cast float as a decimal without rounding and preserving its precision?

Try SELECT CAST(field1 AS DECIMAL(10,2)) field1 and replace 10,2 with whatever precision you need.

How to write subquery inside the OUTER JOIN Statement

You need the "correlation id" (the "AS SS" thingy) on the sub-select to reference the fields in the "ON" condition. The id's assigned inside the sub select are not usable in the join.

SELECT
       cs.CUSID
       ,dp.DEPID
FROM
    CUSTMR cs
        LEFT OUTER JOIN (
            SELECT
                    DEPID
                    ,DEPNAME
                FROM
                    DEPRMNT 
                WHERE
                    dp.DEPADDRESS = 'TOKYO'
        ) ss
            ON (
                ss.DEPID = cs.CUSID
                AND ss.DEPNAME = cs.CUSTNAME
            )
WHERE
    cs.CUSID != '' 

What is the best way to convert an array to a hash in Ruby

Simply use Hash[*array_variable.flatten]

For example:

a1 = ['apple', 1, 'banana', 2]
h1 = Hash[*a1.flatten(1)]
puts "h1: #{h1.inspect}"

a2 = [['apple', 1], ['banana', 2]]
h2 = Hash[*a2.flatten(1)]
puts "h2: #{h2.inspect}"

Using Array#flatten(1) limits the recursion so Array keys and values work as expected.

Measure string size in Bytes in php

You can use mb_strlen() to get the byte length using a encoding that only have byte-characters, without worring about multibyte or singlebyte strings. For example, as drake127 saids in a comment of mb_strlen, you can use '8bit' encoding:

<?php
    $string = 'Cién cañones por banda';
    echo mb_strlen($string, '8bit');
?>

You can have problems using strlen function since php have an option to overload strlen to actually call mb_strlen. See more info about it in http://php.net/manual/en/mbstring.overload.php

For trim the string by byte length without split in middle of a multibyte character you can use:

mb_strcut(string $str, int $start [, int $length [, string $encoding ]] )

How to set specific Java version to Maven

Adding my two cents and explicitly providing the solution.

I have two JDKs installed on my Windows Machine - JDK 1.5 and JDK 1.6.

My default (and set to windows system environment variable) JAVA_HOME is set to JDK 1.5.

However, I have a maven project that I need to build (i.e., JBehave Tutorial's Etsy.com) using JDK 1.6.

My solution in this scenario (which worked!), is as suggested by @DanielBarbarian to set it in mvn.bat.

For some not familiar with window's batch file, I just basically added the set JAVA_HOME=<path_to_other_jdk> line after @REM ==== START VALIDATION ==== in mvn.bat (i.e., %MAVEN_HOME%\bin\mvn.bat):

@REM ==== START VALIDATION ====
set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_45\jre
if not "%JAVA_HOME%" == "" goto OkJHome

Javascript extends class

Douglas Crockford has some very good explanations of inheritance in JavaScript:

  1. prototypal inheritance: the 'natural' way to do things in JavaScript
  2. classical inheritance: closer to what you find in most OO languages, but kind of runs against the grain of JavaScript

Android get image path from drawable as string

If you are planning to get the image from its path, it's better to use Assets instead of trying to figure out the path of the drawable folder.

    InputStream stream = getAssets().open("image.png");
    Drawable d = Drawable.createFromStream(stream, null);

Alternating Row Colors in Bootstrap 3 - No Table

You can use this code :

.row :nth-child(odd){
  background-color:red;
}
.row :nth-child(even){
  background-color:green;
}

Demo : http://codepen.io/mouhammed/pen/rblsC

Row Offset in SQL Server

Best way to do it without wasting time to order records is like this :

select 0 as tmp,Column1 from Table1 Order by tmp OFFSET 5000000 ROWS FETCH NEXT 50 ROWS ONLY

it takes less than one second!
best solution for large tables.

How many significant digits do floats and doubles have in java?

float: 32 bits (4 bytes) where 23 bits are used for the mantissa (about 7 decimal digits). 8 bits are used for the exponent, so a float can “move” the decimal point to the right or to the left using those 8 bits. Doing so avoids storing lots of zeros in the mantissa as in 0.0000003 (3 × 10-7) or 3000000 (3 × 107). There is 1 bit used as the sign bit.

double: 64 bits (8 bytes) where 52 bits are used for the mantissa (about 16 decimal digits). 11 bits are used for the exponent and 1 bit is the sign bit.

Since we are using binary (only 0 and 1), one bit in the mantissa is implicitly 1 (both float and double use this trick) when the number is non-zero.

Also, since everything is in binary (mantissa and exponents) the conversions to decimal numbers are usually not exact. Numbers like 0.5, 0.25, 0.75, 0.125 are stored exactly, but 0.1 is not. As others have said, if you need to store cents precisely, do not use float or double, use int, long, BigInteger or BigDecimal.

Sources:

http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers

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

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

Server returned HTTP response code: 401 for URL: https

Try This. You need pass the authentication to let the server know its a valid user. You need to import these two packages and has to include a jersy jar. If you dont want to include jersy jar then import this package

import sun.misc.BASE64Encoder;

import com.sun.jersey.core.util.Base64;
import sun.net.www.protocol.http.HttpURLConnection;

and then,

String encodedAuthorizedUser = getAuthantication("username", "password");
URL url = new URL("Your Valid Jira URL");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty ("Authorization", "Basic " + encodedAuthorizedUser );

 public String getAuthantication(String username, String password) {
   String auth = new String(Base64.encode(username + ":" + password));
   return auth;
 }

Moment js date time comparison

I believe you are looking for the query functions, isBefore, isSame, and isAfter.

But it's a bit difficult to tell exactly what you're attempting. Perhaps you are just looking to get the difference between the input time and the current time? If so, consider the difference function, diff. For example:

moment().diff(date_time, 'minutes')

A few other things:

  • There's an error in the first line:

      var date_time = 2013-03-24 + 'T' + 10:15:20:12 + 'Z'
    

    That's not going to work. I think you meant:

      var date_time = '2013-03-24' + 'T' + '10:15:20:12' + 'Z';
    

    Of course, you might as well:

      var date_time = '2013-03-24T10:15:20:12Z';
    
  • You're using: .tz('UTC') incorrectly. .tz belongs to moment-timezone. You don't need to use that unless you're working with other time zones, like America/Los_Angeles.

    If you want to parse a value as UTC, then use:

      moment.utc(theStringToParse)
    

    Or, if you want to parse a local value and convert it to UTC, then use:

      moment(theStringToParse).utc()
    

    Or perhaps you don't need it at all. Just because the input value is in UTC, doesn't mean you have to work in UTC throughout your function.

  • You seem to be getting the "now" instance by moment(new Date()). You can instead just use moment().

Updated

Based on your edit, I think you can just do this:

var date_time = req.body.date + 'T' + req.body.time + 'Z';
var isafter = moment(date_time).isAfter('2014-03-24T01:14:00Z');

Or, if you would like to ensure that your fields are validated to be in the correct format:

var m = moment.utc(req.body.date + ' ' + req.body.time, "YYYY-MM-DD  HH:mm:ss");
var isvalid = m.isValid();
var isafter = m.isAfter('2014-03-24T01:14:00Z');

How do I return clean JSON from a WCF Service?

I faced the same problem, and resolved it by changing the BodyStyle attribut value to "WebMessageBodyStyle.Bare" :

[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetProjectWithGeocodings/{projectId}")]
GeoCod_Project GetProjectWithGeocodings(string projectId);

The returned object will no longer be wrapped.

400 BAD request HTTP error code meaning?

Selecting a HTTP response code is quite an easy task and can be described by simple rules. The only tricky part which is often forgotten is paragraph 6.5 from RFC 7231:

Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.

Rules are as following:

  1. If request was successful, then return 2xx code (3xx for redirect). If there was an internal logic error on a server, then return 5xx. If there is anything wrong in client request, then return 4xx code.
  2. Look through available response code from selected category. If one of them has a name which matches well to your situation, you can use it. Otherwise just fallback to x00 code (200, 400, 500). If you doubt, fallback to x00 code.
  3. Return error description in response body. For 4xx codes it must contain enough information for client developer to understand the reason and fix the client. For 5xx because of security reasons no details must be revealed.
  4. If client needs to distinguish different errors and have different reaction depending on it, define a machine readable and extendible error format and use it everywhere in your API. It is good practice to make that from very beginning.
  5. Keep in mind that client developer may do strange things and try to parse strings which you return as human readable description. And by changing the strings you will break such badly written clients. So always provide machine readable description and try to avoid reporting additional information in text.

So in your case I'd returned 400 error and something like this if "Roman" is obtained from user input and client must have specific reaction:

{
    "error_type" : "unsupported_resource",
    "error_description" : "\"Roman\" is not supported"
}

or a more generic error, if such situation is a bad logic error in a client and is not expected, unless developer made something wrong:

{
    "error_type" : "malformed_json",
    "error_description" : "\"Roman\" is not supported for \"requestedResource\" field"
}

running php script (php function) in linux bash

php -f test.php

See the manual for full details of running PHP from the command line

How to get the type of a variable in MATLAB?

class() function is the equivalent of typeof()

You can also use isa() to check if a variable is of a particular type. If you want to be even more specific, you can use ischar(), isfloat(), iscell(), etc.

Adding a right click menu to an item

Add a contextmenu to your form and then assign it in the control's properties under ContextMenuStrip. Hope this helps :).

Hope this helps:

ContextMenu cm = new ContextMenu();
cm.MenuItems.Add("Item 1");
cm.MenuItems.Add("Item 2");

pictureBox1.ContextMenu = cm;

tmux status bar configuration

I used tmux-powerline to fully pimp my tmux status bar. I was googling for a way to change to background of the status bar when your typing a tmux command. When I stumbled on this post I thought I should mention it for completeness.

Update: This project is in a maintenance mode and no future functionality is likely to be added. tmux-powerline, with all other powerline projects, is replaced by the new unifying powerline. However this project is still functional and can serve as a lightweight alternative for non-python users.

Redirect to a page/URL after alert button is pressed

Working example in php.
First Alert then Redirect works....
Enjoy...

echo "<script>";
echo " alert('Import has successfully Done.');      
        window.location.href='".site_url('home')."';
      </script>";

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

This error is often caused by incompatible jQuery versions. I encountered the same error with a foundation 6 repository. My repository was using jQuery 3, but foundation requires an earlier version. I then changed it and it worked.

If you look at the version of jQuery required by the foundation 5 dependencies it states "jquery": "~2.1.0".

Can you confirm that you are loading the correct version of jQuery?

I hope this helps.

How to create JSON string in C#

If you can't or don't want to use the two built-in JSON serializers (JavaScriptSerializer and DataContractJsonSerializer) you can try the JsonExSerializer library - I use it in a number of projects and works quite well.

What is the proper REST response code for a valid request but an empty data?

At first, I thought a 204 would make sense, but after the discussions, I believe 404 is the only true correct response. Consider the following data:

Users: John, Peter

METHOD  URL                      STATUS  RESPONSE
GET     /users                   200     [John, Peter]
GET     /users/john              200     John
GET     /unknown-url-egaer       404     Not Found
GET     /users/kyle              404     User Not found
GET     /users?name=kyle`        200     []
DELETE  /users/john              204     No Content

Some background:

  1. the search returns an array, it just didn't have any matches but it has content: an empty array.

  2. 404 is of course best known for url's that aren't supported by the requested server, but a missing resource is in fact the same.
    Even though /users/:name is matched with users/kyle, the user Kyle is not available resource so a 404 still applies. It isn't a search query, it is a direct reference by a dynamic url, so 404 it is.

  3. After suggestions in the comments, customizing the message of the 404 is another way of helping out the API consumer to even better distinguish between complete unknown routes and missing entities.

Anyway, my two cents :)

error C2065: 'cout' : undeclared identifier

If you started a project requiring the #include "stdafx.h" line, put it first.

Access parent DataContext from DataTemplate

I was searching how to do something similar in WPF and I got this solution:

<ItemsControl ItemsSource="{Binding MyItems,Mode=OneWay}">
<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <StackPanel Orientation="Vertical" />
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <RadioButton 
            Content="{Binding}" 
            Command="{Binding Path=DataContext.CustomCommand, 
                        RelativeSource={RelativeSource Mode=FindAncestor,      
                        AncestorType={x:Type ItemsControl}} }"
            CommandParameter="{Binding}" />
    </DataTemplate>
</ItemsControl.ItemTemplate>

I hope this works for somebody else. I have a data context which is set automatically to the ItemsControls, and this data context has two properties: MyItems -which is a collection-, and one command 'CustomCommand'. Because of the ItemTemplate is using a DataTemplate, the DataContext of upper levels is not directly accessible. Then the workaround to get the DC of the parent is use a relative path and filter by ItemsControl type.

How to split a string with angularJS

You can try something like this:

$scope.test = "test1,test2";
{{test.split(',')[0]}}

now you will get "test1" while you try {{test.split(',')[0]}}

and you will get "test2" while you try {{test.split(',')[1]}}

here is my plnkr:

http://plnkr.co/edit/jaXOrZX9UO9kmdRMImdN?p=preview

log4net hierarchy and logging levels

DEBUG will show all messages, INFO all besides DEBUG messages, and so on.
Usually one uses either INFO or WARN. This dependens on the company policy.

How do I convert number to string and pass it as argument to Execute Process Task?

Expression: "Total Count: " + (DT_WSTR, 11)@[User::int32Value]

for Int32 -- (-2,147,483,648 to 2,147,483,647)

Why use static_cast<int>(x) instead of (int)x?

It's about how much type-safety you want to impose.

When you write (bar) foo (which is equivalent to reinterpret_cast<bar> foo if you haven't provided a type conversion operator) you are telling the compiler to ignore type safety, and just do as it's told.

When you write static_cast<bar> foo you are asking the compiler to at least check that the type conversion makes sense and, for integral types, to insert some conversion code.


EDIT 2014-02-26

I wrote this answer more than 5 years ago, and I got it wrong. (See comments.) But it still gets upvotes!

The first day of the current month in php using date_modify as DateTime object

Here is what I use.

First day of the month:

date('Y-m-01');

Last day of the month:

date('Y-m-t');

Using multiple property files (via PropertyPlaceholderConfigurer) in multiple projects/modules

You can have multiple <context:property-placeholder /> elements instead of explicitly declaring multiple PropertiesPlaceholderConfigurer beans.

How to remove an appended element with Jquery and why bind or live is causing elements to repeat

If I understand your question correctly, I've made a fiddle that has this working correctly. This issue is with how you're assigning the event handlers and as others have said you have over riding event handlers. The current jQuery best practice is to use on() to register event handlers. Here's a link to the jQuery docs about on: link

Your original solution was pretty close but the way you added the event handlers is a bit confusing. It's considered best practice to not add events to HTML elements. I recommend reading up on Unobstrusive JavaScript.

Here's the JavaScript code. I added a counter variable so you can see that it is working correctly.

$('#answer').on('click', function() {
  feedback('hey there');
});

var counter = 0;

function feedback(message) {

  $('#feedback').remove();

  $('.answers').append('<div id="feedback">' + message + ' ' + counter + '</div>');

  counter++;    
}

How do you redirect HTTPS to HTTP?

If you are looking for an answer where you can redirect specific url/s to http then please update your htaccess like below

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{THE_REQUEST} !/(home/panel/videos|user/profile) [NC] # Multiple urls
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTPS} on
RewriteCond %{THE_REQUEST} /(home/panel/videos|user/profile) [NC] # Multiple urls
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

It worked for me :)

Inner Joining three tables

dbo.tableA AS A INNER JOIN dbo.TableB AS B
ON A.common = B.common INNER JOIN TableC C
ON B.common = C.common

How to fix committing to the wrong Git branch?

4 years late on the topic, but this might be helpful to someone.

If you forgot to create a new branch before committing and committed all on master, no matter how many commits you did, the following approach is easier:

git stash                       # skip if all changes are committed
git branch my_feature
git reset --hard origin/master
git checkout my_feature
git stash pop                   # skip if all changes were committed

Now you have your master branch equals to origin/master and all new commits are on my_feature. Note that my_feature is a local branch, not a remote one.

HashSet vs. List performance

You can use a HybridDictionary which automaticly detects the breaking point, and accepts null-values, making it essentialy the same as a HashSet.

Set inputType for an EditText Programmatically?

This may be of help to others like me who wanted to toggle between password and free-text mode. I tried using the input methods suggested but it only worked in one direction. I could go from password to text but then I could not revert. For those trying to handle a toggle (eg a show Password check box) use

       @Override
        public void onClick(View v)
        {
            if(check.isChecked())
            {
                edit.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                Log.i(TAG, "Show password");
            }
            else
            {
                edit.setTransformationMethod(PasswordTransformationMethod.getInstance());
                Log.i(TAG, "Hide password");
            }
        }

I have to credit this for the solution. Wish I had found that a few hours ago!

How to get request url in a jQuery $.get/ajax request

Since jQuery.get is just a shorthand for jQuery.ajax, another way would be to use the latter one's context option, as stated in the documentation:

The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

So you would use

$.ajax('http://www.example.org', {
  dataType: 'xml',
  data: {'a':1,'b':2,'c':3},
  context: {
    url: 'http://www.example.org'
  }
}).done(function(xml) {alert(this.url});

react change class name on state change

Below is a fully functional example of what I believe you're trying to do (with a functional snippet).

Explanation

Based on your question, you seem to be modifying 1 property in state for all of your elements. That's why when you click on one, all of them are being changed.

In particular, notice that the state tracks an index of which element is active. When MyClickable is clicked, it tells the Container its index, Container updates the state, and subsequently the isActive property of the appropriate MyClickables.

Example

_x000D_
_x000D_
class Container extends React.Component {_x000D_
  state = {_x000D_
    activeIndex: null_x000D_
  }_x000D_
_x000D_
  handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
  render() {_x000D_
    return <div>_x000D_
      <MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
      <MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
      <MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
    </div>_x000D_
  }_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
  handleClick = () => this.props.onClick(this.props.index)_x000D_
  _x000D_
  render() {_x000D_
    return <button_x000D_
      type='button'_x000D_
      className={_x000D_
        this.props.isActive ? 'active' : 'album'_x000D_
      }_x000D_
      onClick={ this.handleClick }_x000D_
    >_x000D_
      <span>{ this.props.name }</span>_x000D_
    </button>_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
  display: block;_x000D_
  margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
  content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
  content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Update: "Loops"

In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.

// New render method for `Container`
render() {
  const clickables = [
    { name: "a" },
    { name: "b" },
    { name: "c" },
  ]

  return <div>
      { clickables.map(function(clickable, i) {
          return <MyClickable key={ clickable.name }
            name={ clickable.name }
            index={ i }
            isActive={ this.state.activeIndex === i }
            onClick={ this.handleClick }
          />
        } )
      }
  </div>
}

Android Studio Gradle Configuration with name 'default' not found

In my case I was using Gradle files that work under Windows but failed on Linux. The include ':SomeProject' and compile project(':SomeProject') were case sensitive and were not found.

How do I plot list of tuples in Python?

If I get your question correctly, you could do something like this.

>>> import matplotlib.pyplot as plt
>>> testList =[(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08), 
 (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09), 
 (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
>>> from math import log
>>> testList2 = [(elem1, log(elem2)) for elem1, elem2 in testList]
>>> testList2
[(0, -16.617236475334405), (1, -17.67799605473062), (2, -18.691431541177973), (3, -18.9767093108359), (4, -19.420021520728017), (5, -19.298411635970396)]
>>> zip(*testList2)
[(0, 1, 2, 3, 4, 5), (-16.617236475334405, -17.67799605473062, -18.691431541177973, -18.9767093108359, -19.420021520728017, -19.298411635970396)]
>>> plt.scatter(*zip(*testList2))
>>> plt.show()

which would give you something like

enter image description here

Or as a line plot,

>>> plt.plot(*zip(*testList2))
>>> plt.show()

enter image description here

EDIT - If you want to add a title and labels for the axis, you could do something like

>>> plt.scatter(*zip(*testList2))
>>> plt.title('Random Figure')
>>> plt.xlabel('X-Axis')
>>> plt.ylabel('Y-Axis')
>>> plt.show()

which would give you

enter image description here

How to add a touch event to a UIView?

Here is ios tapgesture; First you need to create action for GestureRecognizer after write the below code under the action as shown below

- (IBAction)tapgesture:(id)sender

{


[_password resignFirstResponder];


[_username resignFirstResponder];

NSLog(@" TapGestureRecognizer  tapped");

}

Get JSON object from URL

file_get_contents() is not fetching the data from url,then i tried curl and it's working fine.

How to disable all div content

If you wanted to keep the semantics of disabled as follows

<div disabled="disabled"> Your content here </div>

you could add the following CSS

div[disabled=disabled] {
  pointer-events: none;
  opacity: 0.4;
}

the benefit here is that you're not working with classes on the div that you want to work with

How can I make a weak protocol reference in 'pure' Swift (without @objc)

AnyObject is the official way to use a weak reference in Swift.

class MyClass {
    weak var delegate: MyClassDelegate?
}

protocol MyClassDelegate: AnyObject {
}

From Apple:

To prevent strong reference cycles, delegates should be declared as weak references. For more information about weak references, see Strong Reference Cycles Between Class Instances. Marking the protocol as class-only will later allow you to declare that the delegate must use a weak reference. You mark a protocol as being class-only by inheriting from AnyObject, as discussed in Class-Only Protocols.

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-ID276

How to change the text of a button in jQuery?

$("#btnAddProfile").click(function(){
    $("#btnAddProfile").attr('value', 'Save');
 });

PHP 7: Missing VCRUNTIME140.dll

If you've followed Adam's instructions and you're still getting this error make sure you've installed the right variants (x86 or x64).

I had VC14x64 with PHP7x86 and I still got this error. Changing PHP7 to x64 fixed it. It's easy to miss you accidentally installed the wrong version.

How to disable SSL certificate checking with Spring RestTemplate?

For the sake of other developers who finds this question and need another solution that fits not only for unit-tests:

I've found this on a blog (not my solution! Credit to the blog's owner).

TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
        .loadTrustMaterial(null, acceptingTrustStrategy)
        .build();

SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

CloseableHttpClient httpClient = HttpClients.custom()
        .setSSLSocketFactory(csf)
        .build();

HttpComponentsClientHttpRequestFactory requestFactory =
        new HttpComponentsClientHttpRequestFactory();

requestFactory.setHttpClient(httpClient);

RestTemplate restTemplate = new RestTemplate(requestFactory);

What is the best way to detect a mobile device?

I tried some of the ways and then I decided to fill a list manually and do a simple JS check. And in the end the user has to confirm. Because some checks gave false positive or negative.

var isMobile = false;
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Opera Mobile|Kindle|Windows Phone|PSP|AvantGo|Atomic Web Browser|Blazer|Chrome Mobile|Dolphin|Dolfin|Doris|GO Browser|Jasmine|MicroB|Mobile Firefox|Mobile Safari|Mobile Silk|Motorola Internet Browser|NetFront|NineSky|Nokia Web Browser|Obigo|Openwave Mobile Browser|Palm Pre web browser|Polaris|PS Vita browser|Puffin|QQbrowser|SEMC Browser|Skyfire|Tear|TeaShark|UC Browser|uZard Web|wOSBrowser|Yandex.Browser mobile/i.test(navigator.userAgent) && confirm('Are you on a mobile device?')) isMobile = true;

Now, if you want to use jQuery to set the CSS, you could do the following:

$(document).ready(function() {
  if (isMobile) $('link[type="text/css"]').attr('href', '/mobile.css');
});

Since the borders between mobile and fixed devices become fluent and mobile browers are already powerful, checking width and user confirmation will probably be the best for the future (assuming that width in some cases will still be important). Because touches are already converted into mouse-ups and downs.

And concerning the mobile movability, I suggest you to think about Yoav Barnea's idea:

if(typeof window.orientation !== 'undefined'){...}

Press Keyboard keys using a batch file

Just to be clear, you are wanting to launch a program from a batch file and then have the batch file press keys (in your example, the arrow keys) within that launched program?

If that is the case, you aren't going to be able to do that with simply a ".bat" file as the launched would stop the batch file from continuing until it terminated--

My first recommendation would be to use something like AutoHotkey or AutoIt if possible, simply because they both have active forums where you'd find countless examples of people launching applications and sending key presses not to mention tools to simply "record" what you want to do. However you said this is a work computer and you may not be able to load a 3rd party program.. but you aren't without options.

You can use Windows Scripting Host from something like a .vbs file to launch a program and send keys to that process. If you're running a version of Windows that includes PowerShell 2.0 (Windows XP with Service Pack 3, Windows Vista with Service Pack 1, Windows 7, etc.) you can use Windows Scripting Host as a COM object from your PS script or use VB's Intereact class.

The specifics of how to do it are outside the scope of this answer but you can find numerous examples using the methods I just described by searching on SO or Google.

edit: Just to help you get started you can look here:

  1. Automate tasks with Windows Script Host's SendKeys method
  2. A useful thread about SendKeys

Getting Spring Application Context

Not sure how useful this will be, but you can also get the context when you initialize the app. This is the soonest you can get the context, even before an @Autowire.

@SpringBootApplication
public class Application extends SpringBootServletInitializer {
    private static ApplicationContext context;

    // I believe this only runs during an embedded Tomcat with `mvn spring-boot:run`. 
    // I don't believe it runs when deploying to Tomcat on AWS.
    public static void main(String[] args) {
        context = SpringApplication.run(Application.class, args);
        DataSource dataSource = context.getBean(javax.sql.DataSource.class);
        Logger.getLogger("Application").info("DATASOURCE = " + dataSource);

Check if value exists in Postgres array

but if you have other ways to do it please share.

You can compare two arrays. If any of the values in the left array overlap the values in the right array, then it returns true. It's kind of hackish, but it works.

SELECT '{1}'   && '{1,2,3}'::int[];  -- true
SELECT '{1,4}' && '{1,2,3}'::int[];  -- true
SELECT '{4}'   && '{1,2,3}'::int[];  -- false
  • In the first and second query, value 1 is in the right array
  • Notice that the second query is true, even though the value 4 is not contained in the right array
  • For the third query, no values in the left array (i.e., 4) are in the right array, so it returns false

How to set a fixed width column with CSS flexbox

You should use the flex or flex-basis property rather than width. Read more on MDN.

.flexbox .red {
  flex: 0 0 25em;
}

The flex CSS property is a shorthand property specifying the ability of a flex item to alter its dimensions to fill available space. It contains:

flex-grow: 0;     /* do not grow   - initial value: 0 */
flex-shrink: 0;   /* do not shrink - initial value: 1 */
flex-basis: 25em; /* width/height  - initial value: auto */

A simple demo shows how to set the first column to 50px fixed width.

_x000D_
_x000D_
.flexbox {_x000D_
  display: flex;_x000D_
}_x000D_
.red {_x000D_
  background: red;_x000D_
  flex: 0 0 50px;_x000D_
}_x000D_
.green {_x000D_
  background: green;_x000D_
  flex: 1;_x000D_
}_x000D_
.blue {_x000D_
  background: blue;_x000D_
  flex: 1;_x000D_
}
_x000D_
<div class="flexbox">_x000D_
  <div class="red">1</div>_x000D_
  <div class="green">2</div>_x000D_
  <div class="blue">3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


See the updated codepen based on your code.

Convert String to Carbon

Why not try using the following:

$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');   

Changes in import statement python3

Relative import happens whenever you are importing a package relative to the current script/package.

Consider the following tree for example:

mypkg
+-- base.py
+-- derived.py

Now, your derived.py requires something from base.py. In Python 2, you could do it like this (in derived.py):

from base import BaseThing

Python 3 no longer supports that since it's not explicit whether you want the 'relative' or 'absolute' base. In other words, if there was a Python package named base installed in the system, you'd get the wrong one.

Instead it requires you to use explicit imports which explicitly specify location of a module on a path-alike basis. Your derived.py would look like:

from .base import BaseThing

The leading . says 'import base from module directory'; in other words, .base maps to ./base.py.

Similarly, there is .. prefix which goes up the directory hierarchy like ../ (with ..mod mapping to ../mod.py), and then ... which goes two levels up (../../mod.py) and so on.

Please however note that the relative paths listed above were relative to directory where current module (derived.py) resides in, not the current working directory.


@BrenBarn has already explained the star import case. For completeness, I will have to say the same ;).

For example, you need to use a few math functions but you use them only in a single function. In Python 2 you were permitted to be semi-lazy:

def sin_degrees(x):
    from math import *
    return sin(degrees(x))

Note that it already triggers a warning in Python 2:

a.py:1: SyntaxWarning: import * only allowed at module level
  def sin_degrees(x):

In modern Python 2 code you should and in Python 3 you have to do either:

def sin_degrees(x):
    from math import sin, degrees
    return sin(degrees(x))

or:

from math import *

def sin_degrees(x):
    return sin(degrees(x))

How to set time delay in javascript

you can use of promise

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

use

console.log("Hello");
sleep(2000).then(() => { console.log("World!"); });

or

console.log("Hello");
await sleep(2000);
console.log("World!");

Where to place $PATH variable assertions in zsh?

tl;dr version: use ~/.zshrc

And read the man page to understand the differences between:

~/.zshrc, ~/.zshenv and ~/.zprofile.


Regarding my comment

In my comment attached to the answer kev gave, I said:

This seems to be incorrect - /etc/profile isn't listed in any zsh documentation I can find.

This turns out to be partially incorrect: /etc/profile may be sourced by zsh. However, this only occurs if zsh is "invoked as sh or ksh"; in these compatibility modes:

The usual zsh startup/shutdown scripts are not executed. Login shells source /etc/profile followed by $HOME/.profile. If the ENV environment variable is set on invocation, $ENV is sourced after the profile scripts. The value of ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before being interpreted as a pathname. [man zshall, "Compatibility"].

The ArchWiki ZSH link says:

At login, Zsh sources the following files in this order:
/etc/profile
This file is sourced by all Bourne-compatible shells upon login

This implys that /etc/profile is always read by zsh at login - I haven't got any experience with the Arch Linux project; the wiki may be correct for that distribution, but it is not generally correct. The information is incorrect compared to the zsh manual pages, and doesn't seem to apply to zsh on OS X (paths in $PATH set in /etc/profile do not make it to my zsh sessions).



To address the question:

where exactly should I be placing my rvm, python, node etc additions to my $PATH?

Generally, I would export my $PATH from ~/.zshrc, but it's worth having a read of the zshall man page, specifically the "STARTUP/SHUTDOWN FILES" section - ~/.zshrc is read for interactive shells, which may or may not suit your needs - if you want the $PATH for every zsh shell invoked by you (both interactive and not, both login and not, etc), then ~/.zshenv is a better option.

Is there a specific file I should be using (i.e. .zshenv which does not currently exist in my installation), one of the ones I am currently using, or does it even matter?

There's a bunch of files read on startup (check the linked man pages), and there's a reason for that - each file has it's particular place (settings for every user, settings for user-specific, settings for login shells, settings for every shell, etc).
Don't worry about ~/.zshenv not existing - if you need it, make it, and it will be read.

.bashrc and .bash_profile are not read by zsh, unless you explicitly source them from ~/.zshrc or similar; the syntax between bash and zsh is not always compatible. Both .bashrc and .bash_profile are designed for bash settings, not zsh settings.

CSS3 equivalent to jQuery slideUp and slideDown?

I would recommend using the jQuery Transit Plugin which uses the CSS3 transform property, which works great on mobile devices due to the fact that most support hardware acceleration to give that native look and feel.

JS Fiddle Example

HTML:

<div class="moveMe">
    <button class="moveUp">Move Me Up</button>
    <button class="moveDown">Move Me Down</button>
    <button class="setUp">Set Me Up</button>
    <button class="setDown">Set Me Down</button>
 </div>

Javascript:

$(".moveUp").on("click", function() {
    $(".moveMe").transition({ y: '-=5' });
});

$(".moveDown").on("click", function() {
    $(".moveMe").transition({ y: '+=5' });
});

$(".setUp").on("click", function() {
    $(".moveMe").transition({ y: '0px' });
});

$(".setDown").on("click", function() {
    $(".moveMe").transition({ y: '200px' });
});

How can I format my grep output to show line numbers at the end of the line, and also the hit count?

Just thought I'd something that might help you in the future. To search multiple string and output line numbers and browse thru the output, type:

egrep -ne 'null|three'

will show:

2:example two null,  
3:example three,  
4:example four null,   

egrep -ne 'null|three' | less

will display output in a less session

HTH Jun

How to set date format in HTML date input tag?

I made a lot of research and I don't think one can force format of the <input type="date">. The browser select the local format, and depending on user settings, if the user's language is in English, the date will be displayed to the English format (mm/dd/yyyy).

In my opinion, the best solution is to use a plugin to control the display.

Jquery DatePicker seems a good option since you can force the localization, date format ...

Pandas groupby month and year

You can use either resample or Grouper (which resamples under the hood).

First make sure that the datetime column is actually of datetimes (hit it with pd.to_datetime). It's easier if it's a DatetimeIndex:

In [11]: df1
Out[11]:
            abc  xyz
Date
2013-06-01  100  200
2013-06-03  -20   50
2013-08-15   40   -5
2014-01-20   25   15
2014-02-21   60   80

In [12]: g = df1.groupby(pd.Grouper(freq="M"))  # DataFrameGroupBy (grouped by Month)

In [13]: g.sum()
Out[13]:
            abc  xyz
Date
2013-06-30   80  250
2013-07-31  NaN  NaN
2013-08-31   40   -5
2013-09-30  NaN  NaN
2013-10-31  NaN  NaN
2013-11-30  NaN  NaN
2013-12-31  NaN  NaN
2014-01-31   25   15
2014-02-28   60   80

In [14]: df1.resample("M", how='sum')  # the same
Out[14]:
            abc  xyz
Date
2013-06-30   40  125
2013-07-31  NaN  NaN
2013-08-31   40   -5
2013-09-30  NaN  NaN
2013-10-31  NaN  NaN
2013-11-30  NaN  NaN
2013-12-31  NaN  NaN
2014-01-31   25   15
2014-02-28   60   80

Note: Previously pd.Grouper(freq="M") was written as pd.TimeGrouper("M"). The latter is now deprecated since 0.21.


I had thought the following would work, but it doesn't (due to as_index not being respected? I'm not sure.). I'm including this for interest's sake.

If it's a column (it has to be a datetime64 column! as I say, hit it with to_datetime), you can use the PeriodIndex:

In [21]: df
Out[21]:
        Date  abc  xyz
0 2013-06-01  100  200
1 2013-06-03  -20   50
2 2013-08-15   40   -5
3 2014-01-20   25   15
4 2014-02-21   60   80

In [22]: pd.DatetimeIndex(df.Date).to_period("M")  # old way
Out[22]:
<class 'pandas.tseries.period.PeriodIndex'>
[2013-06, ..., 2014-02]
Length: 5, Freq: M

In [23]: per = df.Date.dt.to_period("M")  # new way to get the same

In [24]: g = df.groupby(per)

In [25]: g.sum()  # dang not quite what we want (doesn't fill in the gaps)
Out[25]:
         abc  xyz
2013-06   80  250
2013-08   40   -5
2014-01   25   15
2014-02   60   80

To get the desired result we have to reindex...

HTTP GET Request in Node.js Express

Use reqclient: not designed for scripting purpose like request or many other libraries. Reqclient allows in the constructor specify many configurations useful when you need to reuse the same configuration again and again: base URL, headers, auth options, logging options, caching, etc. Also has useful features like query and URL parsing, automatic query encoding and JSON parsing, etc.

The best way to use the library is create a module to export the object pointing to the API and the necessary configurations to connect with:

Module client.js:

let RequestClient = require("reqclient").RequestClient

let client = new RequestClient({
  baseUrl: "https://myapp.com/api/v1",
  cache: true,
  auth: {user: "admin", pass: "secret"}
})

module.exports = client

And in the controllers where you need to consume the API use like this:

let client = require('client')
//let router = ...

router.get('/dashboard', (req, res) => {
  // Simple GET with Promise handling to https://myapp.com/api/v1/reports/clients
  client.get("reports/clients")
    .then(response => {
       console.log("Report for client", response.userId)  // REST responses are parsed as JSON objects
       res.render('clients/dashboard', {title: 'Customer Report', report: response})
    })
    .catch(err => {
      console.error("Ups!", err)
      res.status(400).render('error', {error: err})
    })
})

router.get('/orders', (req, res, next) => {
  // GET with query (https://myapp.com/api/v1/orders?state=open&limit=10)
  client.get({"uri": "orders", "query": {"state": "open", "limit": 10}})
    .then(orders => {
      res.render('clients/orders', {title: 'Customer Orders', orders: orders})
    })
    .catch(err => someErrorHandler(req, res, next))
})

router.delete('/orders', (req, res, next) => {
  // DELETE with params (https://myapp.com/api/v1/orders/1234/A987)
  client.delete({
    "uri": "orders/{client}/{id}",
    "params": {"client": "A987", "id": 1234}
  })
  .then(resp => res.status(204))
  .catch(err => someErrorHandler(req, res, next))
})

reqclient supports many features, but it has some that are not supported by other libraries: OAuth2 integration and logger integration with cURL syntax, and always returns native Promise objects.

Matching an empty input box using CSS

This worked for me:

For the HTML, add the required attribute to the input element

<input class="my-input-element" type="text" placeholder="" required />

For the CSS, use the :invalid selector to target the empty input

input.my-input-element:invalid {

}

Notes:

  • About required from w3Schools.com: "When present, it specifies that an input field must be filled out before submitting the form."

$_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST'

If your application needs to react on request of type post, use this:

if(strtoupper($_SERVER['REQUEST_METHOD']) === 'POST') { // if form submitted with post method
    // validate request, 
    // manage post request differently, 
    // log or don't log request,
    // redirect to avoid resubmition on F5 etc
}

If your application needs to react on any data received through post request, use this:

if(!empty($_POST)) {  // if received any post data
   // process $_POST values, 
   // save data to DB,
   // ... 
}

if(!empty($_FILES)) { // if received any "post" files
   // validate uploaded FILES
   // move to uploaded dir
   // ...
}

It is implementation specific, but you a going to use both, + $_FILES superglobal.

Change div height on button click

You just forgot the quotes. Change your code according to this:

    <button type="button" onClick = "document.getElementById('chartdiv').style.height = '200px'">Click Me!</button>

should work.

Violation Long running JavaScript task took xx ms

I found a solution in Apache Cordova source code. They implement like this:

var resolvedPromise = typeof Promise == 'undefined' ? null : Promise.resolve();
var nextTick = resolvedPromise ? function(fn) { resolvedPromise.then(fn); } : function(fn) { setTimeout(fn); };

Simple implementation, but smart way.

Over the Android 4.4, use Promise. For older browsers, use setTimeout()


Usage:

nextTick(function() {
  // your code
});

After inserting this trick code, all warning messages are gone.

How do you use math.random to generate random ints?

int abc= (Math.random()*100);//  wrong 

you wil get below error message

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from double to int

int abc= (int) (Math.random()*100);// add "(int)" data type

,known as type casting

if the true result is

int abc= (int) (Math.random()*1)=0.027475

Then you will get output as "0" because it is a integer data type.

int abc= (int) (Math.random()*100)=0.02745

output:2 because (100*0.02745=2.7456...etc)

PHP Warning: Invalid argument supplied for foreach()

You should check that what you are passing to foreach is an array by using the is_array function

If you are not sure it's going to be an array you can always check using the following PHP example code:

if (is_array($variable)) {

  foreach ($variable as $item) {
   //do something
  }
}

SFTP in Python? (platform independent)

You should check out pysftp https://pypi.python.org/pypi/pysftp it depends on paramiko, but wraps most common use cases to just a few lines of code.

import pysftp
import sys

path = './THETARGETDIRECTORY/' + sys.argv[1]    #hard-coded
localpath = sys.argv[1]

host = "THEHOST.com"                    #hard-coded
password = "THEPASSWORD"                #hard-coded
username = "THEUSERNAME"                #hard-coded

with pysftp.Connection(host, username=username, password=password) as sftp:
    sftp.put(localpath, path)

print 'Upload done.'

Loop through checkboxes and count each one checked or unchecked

Using Selectors

You can get all checked checkboxes like this:

var boxes = $(":checkbox:checked");

And all non-checked like this:

var nboxes = $(":checkbox:not(:checked)");

You could merely cycle through either one of these collections, and store those names. If anything is absent, you know it either was or wasn't checked. In PHP, if you had an array of names which were checked, you could simply do an in_array() request to know whether or not any particular box should be checked at a later date.

Serialize

jQuery also has a serialize method that will maintain the state of your form controls. For instance, the example provided on jQuery's website follows:

single=Single2&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio2

This will enable you to keep the information for which elements were checked as well.

How can a divider line be added in an Android RecyclerView?

Here is the code for a simple custom divider (vertical divider / 1dp height / black ):

It suppose you have Support Library:

compile "com.android.support:recyclerview-v7:25.1.1"

java code

    DividerItemDecoration divider = new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL);
    divider.setDrawable(ContextCompat.getDrawable(getBaseContext(), R.drawable.my_custom_divider));
    recyclerView.addItemDecoration(divider);

then the custom_divider.xml file sample :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <size android:height="1dp" />
    <solid android:color="@android:color/black" />
</shape>

Subtract days from a DateTime

The object (i.e. destination variable) for the AddDays method can't be the same as the source.

Instead of:

DateTime today = DateTime.Today;
today.AddDays(-7);

Try this instead:

DateTime today = DateTime.Today;
DateTime sevenDaysEarlier = today.AddDays(-7);

Uncaught ReferenceError: function is not defined with onclick

Never use .onclick(), or similar attributes from a userscript! (It's also poor practice in a regular web page).

The reason is that userscripts operate in a sandbox ("isolated world"), and onclick operates in the target-page scope and cannot see any functions your script creates.

Always use addEventListener()Doc (or an equivalent library function, like jQuery .on()).

So instead of code like:

something.outerHTML += '<input onclick="resetEmotes()" id="btnsave" ...>'


You would use:

something.outerHTML += '<input id="btnsave" ...>'

document.getElementById ("btnsave").addEventListener ("click", resetEmotes, false);

For the loop, you can't pass data to an event listener like that See the doc. Plus every time you change innerHTML like that, you destroy the previous event listeners!

Without refactoring your code much, you can pass data with data attributes. So use code like this:

for (i = 0; i < EmoteURLLines.length; i++) {
    if (checkIMG (EmoteURLLines[i])) {
        localStorage.setItem ("nameEmotes", JSON.stringify (EmoteNameLines));
        localStorage.setItem ("urlEmotes", JSON.stringify (EmoteURLLines));
        localStorage.setItem ("usageEmotes", JSON.stringify (EmoteUsageLines));
        if (i == 0) {
            console.log (resetSlot ());
        }
        emoteTab[2].innerHTML  += '<span style="cursor:pointer;" id="' 
                                + EmoteNameLines[i] 
                                + '" data-usage="' + EmoteUsageLines[i] + '">'
                                + '<img src="' + EmoteURLLines[i] + '" /></span>'
                                ;
    } else {
        alert ("The maximum emote (" + EmoteNameLines[i] + ") size is (36x36)");
    }
}
//-- Only add events when innerHTML overwrites are done.
var targetSpans = emoteTab[2].querySelectorAll ("span[data-usage]");
for (var J in targetSpans) {
    targetSpans[J].addEventListener ("click", appendEmote, false);
}

Where appendEmote is like:

function appendEmote (zEvent) {
    //-- this and the parameter are special in event handlers.  see the linked doc.
    var emoteUsage  = this.getAttribute ("data-usage");
    shoutdata.value += emoteUsage;
}


WARNINGS:

  • Your code reuses the same id for several elements. Don't do this, it's invalid. A given ID should occur only once per page.
  • Every time you use .outerHTML or .innerHTML, you trash any event handlers on the affected nodes. If you use this method beware of that fact.

Why would $_FILES be empty when uploading files to PHP?

Check your php.ini for enable_post_data_reading=On , because:

Disabling this option causes $_POST and $_FILES not to be populated. The only way to read postdata will then be through the php://input stream wrapper. (... )

In http://php.net/manual/en/ini.core.php#ini.enable-post-data-reading

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

You can use less code, writing this:

    $users = DB::table('really_long_table_name')
       ->get(array('really_long_table_name.field_very_long_name as short_name'));

And of course if you want to select more fields, just write a "," and add more:

 $users = DB::table('really_long_table_name')
       ->get(array('really_long_table_name.field_very_long_name as short_name', 'really_long_table_name.another_field as other', 'and_another'));

This is very practical when you use a joins complex query

How to open some ports on Ubuntu?

If you want to open it for a range and for a protocol

ufw allow 11200:11299/tcp
ufw allow 11200:11299/udp

How to get date representing the first day of a month?

SELECT  CAST(FLOOR(CAST(DATEADD(d, 1 - DAY(GETDATE()), GETDATE()) AS FLOAT)) AS DATETIME)

How to create an empty matrix in R?

I'd be cautious as dismissing something as a bad idea because it is slow. If it is a part of the code that does not take much time to execute then the slowness is irrelevant. I just used the following code:

for (ic in 1:(dim(centroid)[2]))
{
cluster[[ic]]=matrix(,nrow=2,ncol=0)
}
# code to identify cluster=pindex[ip] to which to add the point
if(pdist[ip]>-1)
{
cluster[[pindex[ip]]]=cbind(cluster[[pindex[ip]]],points[,ip])
}

for a problem that ran in less than 1 second.

Maven compile with multiple src directories

This worked for me

<build>
    <sourceDirectory>.</sourceDirectory>
    <plugins>
        <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
        <includes>
            <include>src/main/java/**/*.java</include>
            <include>src/main2/java/**/*.java</include>
        </includes>
        </configuration>
        </plugin>
    </plugins>
</build>

How do I find the index of a character in a string in Ruby?

You can use this

"abcdefg".index('c')   #=> 2

Downloading MySQL dump from command line

If you are running the MySQL other than default port:

mysqldump.exe -u username -p -P PORT_NO database > backup.sql

Difference between & and && in Java?

& is bitwise. && is logical.

& evaluates both sides of the operation.
&& evaluates the left side of the operation, if it's true, it continues and evaluates the right side.

Bad Gateway 502 error with Apache mod_proxy and Tomcat

You can avoid global timeouts or having to virtual hosts by specifying the proxy timeouts in the ProxyPass directive as follows:

ProxyPass /svc http://example.com/svc timeout=600
ProxyPassReverse /svc http://example.com/svc timeout=600

Notice timeout=600 seconds.

However this does not always work when you have load balancer. In that case you must add the timeouts in both the places (tested in Apache 2.2.31)

Load Balancer example:

<Proxy "balancer://mycluster">
     BalancerMember "http://member1:8080/svc" timeout=600
     BalancerMember "http://member2:8080/svc" timeout=600
</Proxy> 

ProxyPass /svc "balancer://mycluster" timeout=600
ProxyPassReverse /svc "balancer://mycluster" timeout=600

A side note: the timeout=600 on ProxyPass was not required when Chrome was the client (I don;t know why) but without this timeout on ProxyPass Internet Explorer (11) aborts saying connection reset by server.

My theory is that the :

ProxyPass timeout is used between the client(browser) and the Apache.

BalancerMember timeout is used between the Apache and the backend.

To those who use Tomcat or other backed you may also want to pay attention to the HTTP Connector timeouts.

How to find the Target *.exe file of *.appref-ms

The app is stored in %LocalAppData% in your %UserProfile%. So the full path could be:

C:\Users\username\AppData\Local\GitHub

How to update Android Studio automatically?

On the startup screen you can use the configure button to check for updates.

1) Choose configure > Check for Update enter image description here

2) Download the latest updates

enter image description here

In c++ what does a tilde "~" before a function name signify?

As others have noted, in the instance you are asking about it is the destructor for class Stack.

But taking your question exactly as it appears in the title:

In c++ what does a tilde “~” before a function name signify?

there is another situation. In any context except immediately before the name of a class (which is the destructor context), ~ is the one's complement (or bitwise not) operator. To be sure it does not come up very often, but you can imagine a case like

if (~getMask()) { ...

which looks similar, but has a very different meaning.

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

jQuery selector first td of each row

You should use :first-child instead of :first:

Sounds like you're wanting to iterate through them. You can do this using .each().

Example:

$('td:first-child').each(function() {
    console.log($(this).text());
});

Result:

nonono
nonono2
nonono3

Alernatively if you're not wanting to iterate:

$('td:first-child').css('background', '#000');

JSFiddle demo.

convert string date to java.sql.Date

worked for me too:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date parsed = null;
    try {
        parsed = sdf.parse("02/01/2014");
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    java.sql.Date data = new java.sql.Date(parsed.getTime());
    contato.setDataNascimento( data);

    // Contato DataNascimento era Calendar
    //contato.setDataNascimento(Calendar.getInstance());         

    // grave nessa conexão!!! 
    ContatoDao dao = new ContatoDao("mysql");           

    // método elegante 
    dao.adiciona(contato); 
    System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());

How to use If Statement in Where Clause in SQL?

Nto sure which RDBMS you are using, but if it is SQL Server you could look at rather using a CASE statement

Evaluates a list of conditions and returns one of multiple possible result expressions.

The CASE expression has two formats:

The simple CASE expression compares an expression to a set of simple expressions to determine the result.

The searched CASE expression evaluates a set of Boolean expressions to determine the result.

Both formats support an optional ELSE argument.

How do you access the element HTML from within an Angular attribute directive?

So actually, my comment that you should do a console.log(el.nativeElement) should have pointed you in the right direction, but I didn't expect the output to be just a string representing the DOM Element.

What you have to do to inspect it in the way it helps you with your problem, is to do a console.log(el) in your example, then you'll have access to the nativeElement object and will see a property called innerHTML.

Which will lead to the answer to your original question:

let myCurrentContent:string = el.nativeElement.innerHTML; // get the content of your element
el.nativeElement.innerHTML = 'my new content'; // set content of your element

Update for better approach:

Since it's the accepted answer and web workers are getting more important day to day (and it's considered best practice anyway) I want to add this suggestion by Mark Rajcok here.

The best way to manipulate DOM Elements programmatically is using the Renderer:

constructor(private _elemRef: ElementRef, private _renderer: Renderer) { 
    this._renderer.setElementProperty(this._elemRef.nativeElement, 'innerHTML', 'my new content');
}

Edit

Since Renderer is deprecated now, use Renderer2 instead with setProperty


Update:

This question with its answer explained the console.log behavior.

Which means that console.dir(el.nativeElement) would be the more direct way of accessing the DOM Element as an "inspectable" Object in your console for this situation.


Hope this helped.

Comparing date part only without comparing time in JavaScript

You can use fp_incr(0). Which sets the timezone part to midnight and returns a date object.

Connection failed: SQLState: '01000' SQL Server Error: 10061

I had the same error which was coming and dont need to worry about this error, just restart the server and restart the SQL services. This issue comes when there is low disk space issue and system will go into hung state and then the sql services will stop automatically.

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

After hours of analysis reading tons of logs and internet, finally found problem.

If you use docker and php 7.4 (my case) you probably get error because default security level in OpenSSL it too high for wsdl cert. Even if you disable verify and allow self-signed in SoapClient options.

You need lower seclevel in /etc/ssl/openssl.cnf from DEFAULT@SECLEVEL=2 to

DEFAULT@SECLEVEL=1

Or just add into Dockerfile

RUN sed -i "s|DEFAULT@SECLEVEL=2|DEFAULT@SECLEVEL=1|g" /etc/ssl/openssl.cnf

Source: https://github.com/dotnet/runtime/issues/30667#issuecomment-566482876


You can verify it by run on container

curl -A 'cURL User Agent' -4 https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/Auth?wsdl

Before that change I got error:

SSL routines:tls_process_ske_dhe:dh key too small

Vue.js unknown custom element

Be sure that you have added the component to the components.

For example:

export default {
data() {
    return {}
},
components: {
    'lead-status-modal': LeadStatusModal,
},
}

Replacing instances of a character in a string

How about this:

sentence = 'After 1500 years of that thinking surpressed'

sentence = sentence.lower()

def removeLetter(text,char):

    result = ''
    for c in text:
        if c != char:
            result += c
    return text.replace(char,'*')
text = removeLetter(sentence,'a')

Change HTML email body font type and size in VBA

FYI I did a little research as well and if the name of the font-family you want to apply contains spaces (as an example I take Gill Alt One MT Light), you should write it this way :

strbody= "<BODY style=" & Chr(34) & "font-family:Gill Alt One MT Light" & Chr(34) & ">" & YOUR_TEXT & "</BODY>"

can we use xpath with BeautifulSoup?

I can confirm that there is no XPath support within Beautiful Soup.

Python 2.7: %d, %s, and float()

Try the following:

print "First is: %f" % (first)
print "Second is: %f" % (second)

I am unsure what answer is. But apart from that, this will be:

print "DONE: %f DIVIDED BY %f EQUALS %f, SWEET MATH BRO!" % (first, second, ans)

There's a lot of text on Format String Specifiers. You can google it and get a list of specifiers. One thing I forgot to note:

If you try this:

print "First is: %s" % (first)

It converts the float value in first to a string. So that would work as well.

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

To add WebAPI in my MVC 5 project.

  1. Open NuGet Package manager console and run

    PM> Install-Package Microsoft.AspNet.WebApi
    
  2. Add references to System.Web.Routing, System.Web.Net and System.Net.Http dlls if not there already

  3. Right click controllers folder > add new item > web > Add Web API controller

  4. Web.config will be modified accordingly by VS

  5. Add Application_Start method if not there already

    protected void Application_Start()
    {
        //this should be line #1 in this method
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
    
  6. Add the following class (I added in global.asax.cs file)

    public static class WebApiConfig
    {
         public static void Register(HttpConfiguration config)
         {
             // Web API routes
             config.MapHttpAttributeRoutes();
    
             config.Routes.MapHttpRoute(
                 name: "DefaultApi",
                 routeTemplate: "api/{controller}/{id}",
                 defaults: new { id = RouteParameter.Optional }
             );
         }
     }
    
  7. Modify web api method accordingly

    namespace <Your.NameSpace.Here>
    {
        public class VSController : ApiController
        {
            // GET api/<controller>   : url to use => api/vs
            public string Get()
            {
                return "Hi from web api controller";
            }
    
            // GET api/<controller>/5   : url to use => api/vs/5
            public string Get(int id)
            {
                return (id + 1).ToString();
            }
        }
    }
    
  8. Rebuild and test

  9. Build a simple html page

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>    
        <script src="../<path_to_jquery>/jquery-1.9.1.min.js"></script>
        <script type="text/javascript">
            var uri = '/api/vs';
            $(document).ready(function () {
                $.getJSON(uri)
                .done(function (data) {
                    alert('got: ' + data);
                });
    
                $.ajax({
                    url: '/api/vs/5',
                    async: true,
                    success: function (data) {
                        alert('seccess1');
                        var res = parseInt(data);
                        alert('got res=' + res);
                    }
                });
            });
        </script>
    </head>
    <body>
    ....
    </body>
    </html>
    

Disable automatic sorting on the first column when using jQuery DataTables

var table;

$(document).ready(function() {

    //datatables
    table = $('#userTable').DataTable({ 

        "processing": true, //Feature control the processing indicator.
        "serverSide": true, //Feature control DataTables' server-side processing mode.
        "order": [], //Initial no order.
         "aaSorting": [],
        // Load data for the table's content from an Ajax source
        "ajax": {
            "url": "<?php echo base_url().'admin/ajax_list';?>",
            "type": "POST"
        },

        //Set column definition initialisation properties.
        "columnDefs": [
        { 
            "targets": [ ], //first column / numbering column
            "orderable": false, //set not orderable
        },
        ],

    });

});

set

"targets": [0]

to

 "targets": [ ]

fork() child and parent processes

Start by reading the fork man page as well as the getppid / getpid man pages.

From fork's

On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and errno will be set appropriately.

So this should be something down the lines of

if ((pid=fork())==0){
    printf("yada yada %u and yada yada %u",getpid(),getppid());
}
else{ /* avoids error checking*/
    printf("Dont yada yada me, im your parent with pid %u ", getpid());
}

As to your question:

This is the child process. My pid is 22163 and my parent's id is 0.

This is the child process. My pid is 22162 and my parent's id is 22163.

fork() executes before the printf. So when its done, you have two processes with the same instructions to execute. Therefore, printf will execute twice. The call to fork() will return 0 to the child process, and the pid of the child process to the parent process.

You get two running processes, each one will execute this instruction statement:

printf ("... My pid is %d and my parent's id is %d",getpid(),0); 

and

printf ("... My pid is %d and my parent's id is %d",getpid(),22163);  

~

To wrap it up, the above line is the child, specifying its pid. The second line is the parent process, specifying its id (22162) and its child's (22163).

How to set the initial zoom/width for a webview

in Kotlin You can use,

webView.isScrollbarFadingEnabled = true
webView.setInitialScale(100)

Enabling refreshing for specific html elements only

Try this in your script:

$("#YourElement").html(htmlData);

I do this in my table refreshment.

Send POST data via raw json with postman

I was facing the same problem, following code worked for me:

$params = (array) json_decode(file_get_contents('php://input'), TRUE);
print_r($params);

Detect whether there is an Internet connection available on Android

Step 1: Create a class AppStatus in your project(you can give any other name also). Then please paste the given below lines into your code:

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;


public class AppStatus {

    private static AppStatus instance = new AppStatus();
    static Context context;
    ConnectivityManager connectivityManager;
    NetworkInfo wifiInfo, mobileInfo;
    boolean connected = false;

    public static AppStatus getInstance(Context ctx) {
        context = ctx.getApplicationContext();
        return instance;
    }

    public boolean isOnline() {
        try {
            connectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        connected = networkInfo != null && networkInfo.isAvailable() &&
                networkInfo.isConnected();
        return connected;


        } catch (Exception e) {
            System.out.println("CheckConnectivity Exception: " + e.getMessage());
            Log.v("connectivity", e.toString());
        }
        return connected;
    }
}

Step 2: Now to check if the your device has network connectivity then just add this code snippet where ever you want to check ...

if (AppStatus.getInstance(this).isOnline()) {

    Toast.makeText(this,"You are online!!!!",8000).show();

} else {

    Toast.makeText(this,"You are not online!!!!",8000).show();
    Log.v("Home", "############################You are not online!!!!");    
}

Apache Spark: The number of cores vs. the number of executors

There is a small issue in the First two configurations i think. The concepts of threads and cores like follows. The concept of threading is if the cores are ideal then use that core to process the data. So the memory is not fully utilized in first two cases. If you want to bench mark this example choose the machines which has more than 10 cores on each machine. Then do the bench mark.

But dont give more than 5 cores per executor there will be bottle neck on i/o performance.

So the best machines to do this bench marking might be data nodes which have 10 cores.

Data node machine spec: CPU: Core i7-4790 (# of cores: 10, # of threads: 20) RAM: 32GB (8GB x 4) HDD: 8TB (2TB x 4)

Specify a Root Path of your HTML directory for script links?

As Alexander Jank mentioned <base href="http://www.example.com/default/"> is great. When using sub-domains e.g. default.example.com base works great, because the JS and CSS loads from the said sub-domain and is accessible to both default.example.com and example.com/default

When using the root path, and your JS and CSS files are located in example.com/css, or example.com/js, then the subdomain has no access and the root of the subdomain is not accessible, except using the base.

How to remove last n characters from every element in the R vector

Here is an example of what I would do. I hope it's what you're looking for.

char_array = c("foo_bar","bar_foo","apple","beer")
a = data.frame("data"=char_array,"data2"=1:4)
a$data = substr(a$data,1,nchar(a$data)-3)

a should now contain:

  data data2
1 foo_ 1
2 bar_ 2
3   ap 3
4    b 4

What is the meaning of "operator bool() const"

Member functions of the form

operator TypeName()

are conversion operators. They allow objects of the class type to be used as if they were of type TypeName and when they are, they are converted to TypeName using the conversion function.

In this particular case, operator bool() allows an object of the class type to be used as if it were a bool. For example, if you have an object of the class type named obj, you can use it as

if (obj)

This will call the operator bool(), return the result, and use the result as the condition of the if.

It should be noted that operator bool() is A Very Bad Idea and you should really never use it. For a detailed explanation as to why it is bad and for the solution to the problem, see "The Safe Bool Idiom."

(C++0x, the forthcoming revision of the C++ Standard, adds support for explicit conversion operators. These will allow you to write a safe explicit operator bool() that works correctly without having to jump through the hoops of implementing the Safe Bool Idiom.)

How to edit a JavaScript alert box title?

There's quite a nice 'hack' here - https://stackoverflow.com/a/14565029 where you use an iframe with an empty src to generate the alert / confirm message - it doesn't work on Android (for security's sake) - but may suit your scenario.

PHP - If variable is not empty, echo some html code

I don't see how if(!empty($var)) can create confusion, but I do agree that if ($var) is simpler. – vanneto Mar 8 '12 at 13:33

Because empty has the specific purpose of suppressing errors for nonexistent variables. You don't want to suppress errors unless you need to. The Definitive Guide To PHP's isset And empty explains the problem in detail. – deceze? Mar 9 '12 at 1:24

Focusing on the error suppression part, if the variable is an array where a key being accessed may or may not be defined:

  1. if($web['status']) would produce:

    Notice: Undefined index: status

  2. To access that key without triggering errors:
    1. if(isset($web['status']) && $web['status']) (2nd condition is not tested if the 1st one is FALSE) OR
    2. if(!empty($web['status'])).

However, as deceze? pointed out, a truthy value of a defined variable makes !empty redundant, but you still need to remember that PHP assumes the following examples as FALSE:

  • null
  • '' or ""
  • 0.0
  • 0
  • '0' or "0"
  • '0' + 0 + !3

So if zero is a meaningful status that you want to detect, you should actually use string and numeric comparisons:

  1. Error free and zero detection:

    if(isset($web['status'])){
      if($web['status'] === '0' || $web['status'] === 0 ||
         $web['status'] === 0.0 || $web['status']) {
        // not empty: use the value
      } else {
        // consider it as empty, since status may be FALSE, null or an empty string
      }
    }
    

    The generic condition ($web['status']) should be left at the end of the entire statement.

MySQL compare DATE string with string from DATETIME field

SELECT * FROM sample_table WHERE last_visit = DATE_FORMAT('2014-11-24 10:48:09','%Y-%m-%d %H:%i:%s')

this for datetime format in mysql using DATE_FORMAT(date,format).

E: Unable to locate package mongodb-org

I'm running Ubuntu 14.04; and apt still couldn't find package; I tried all the answers above and more. The URL that worked for me is this:

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list

Source: http://www.liquidweb.com/kb/how-to-install-mongodb-on-ubuntu-14-04/

Check if a property exists in a class

I'm unsure of the context on why this was needed, so this may not return enough information for you but this is what I was able to do:

if(typeof(ModelName).GetProperty("Name of Property") != null)
{
//whatevver you were wanting to do.
}

In my case I'm running through properties from a form submission and also have default values to use if the entry is left blank - so I needed to know if the there was a value to use - I prefixed all my default values in the model with Default so all I needed to do is check if there was a property that started with that.

The model backing the 'ApplicationDbContext' context has changed since the database was created

this comes because you add some property to one of your model and you did not update-Database . to solve this you have to remove it from model or you have to add-migration anyProperName with that properties and Update-database.

How does Java resolve a relative path in new File()?

There is a concept of a working directory.
This directory is represented by a . (dot).
In relative paths, everything else is relative to it.

Simply put the . (the working directory) is where you run your program.
In some cases the working directory can be changed but in general this is
what the dot represents. I think this is C:\JavaForTesters\ in your case.

So test\..\test.txt means: the sub-directory test
in my working directory, then one level up, then the
file test.txt. This is basically the same as just test.txt.

For more details check here.

http://docs.oracle.com/javase/7/docs/api/java/io/File.html

http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

Apache won't run in xampp

I had the same kind of problems. I finally made it to work.

I successfully changed the apache ports to listen to ports not used by other programs Port 443 is used by SSL and Skype

I believe that the XAMPP Control Panel has a bug and I have screen shots in my posts to. I do not have enough credibility on this web site to upload pictures.

I have the whole thing written down with screen shots in the following blog posts:

http://hodentek.blogspot.com/2014/02/one-way-to-handle-port-80-in-use-by.html http://hodentekhelp.blogspot.com/2014/02/on-installing-apache-on-windows-7-64bit.html http://hodentekhelp.blogspot.com/2014/02/do-you-want-to-change-ports-that-skype.html

How to determine whether code is running in DEBUG / RELEASE build?

Apple already includes a DEBUG flag in debug builds, so you don't need to define your own.

You might also want to consider just redefining NSLog to a null operation when not in DEBUG mode, that way your code will be more portable and you can just use regular NSLog statements:

//put this in prefix.pch

#ifndef DEBUG
#undef NSLog
#define NSLog(args, ...)
#endif

What is the difference between Cygwin and MinGW?

Cygwin uses a compatibility layer, while MinGW is native. That is one of the main differences.

How do you check that a number is NaN in JavaScript?

NaN === NaN;        // false
Number.NaN === NaN; // false
isNaN(NaN);         // true
isNaN(Number.NaN);  // true

Equality operator (== and ===) cannot be used to test a value against NaN.

Look at Mozilla Documentation The global NaN property is a value representing Not-A-Numbe

The best way is using 'isNaN()' which is buit-in function to check NaN. All browsers supports the way..

Writing an Excel file in EPPlus

It's best if you worked with DataSets and/or DataTables. Once you have that, ideally straight from your stored procedure with proper column names for headers, you can use the following method:

ws.Cells.LoadFromDataTable(<DATATABLE HERE>, true, OfficeOpenXml.Table.TableStyles.Light8);

.. which will produce a beautiful excelsheet with a nice table!

Now to serve your file, assuming you have an ExcelPackage object as in your code above called pck..

Response.Clear();

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);

Response.BinaryWrite(pck.GetAsByteArray());
Response.End();

How to allow only one radio button to be checked?

All radio buttons have to have the same name:

<input type='radio' name='foo'>

Only 1 radio button of each group of buttons with the same name can be checked.

What is the difference between document.location.href and document.location?

document.location is a synonym for window.location that has been deprecated for almost as long as JavaScript has existed. Don't use it.

location is a structured object, with properties corresponding to the parts of the URL. location.href is the whole URL in a single string. Assigning a string to either is defined to cause the same kind of navigation, so take your pick.

I consider writing to location.href = something to be marginally better as it's slightly more explicit about what it's doing. You generally want to avoid just location = something as it looks misleadingly like a variable assignment. window.location = something is fine though.

How to Update Multiple Array Elements in mongodb

$[] operator selects all nested array ..You can update all array items with '$[]'

.update({"events.profile":10},{$set:{"events.$[].handled":0}},false,true)

Reference

Total memory used by Python process?

Even easier to use than /proc/self/status: /proc/self/statm. It's just a space delimited list of several statistics. I haven't been able to tell if both files are always present.

/proc/[pid]/statm

Provides information about memory usage, measured in pages. The columns are:

  • size (1) total program size (same as VmSize in /proc/[pid]/status)
  • resident (2) resident set size (same as VmRSS in /proc/[pid]/status)
  • shared (3) number of resident shared pages (i.e., backed by a file) (same as RssFile+RssShmem in /proc/[pid]/status)
  • text (4) text (code)
  • lib (5) library (unused since Linux 2.6; always 0)
  • data (6) data + stack
  • dt (7) dirty pages (unused since Linux 2.6; always 0)

Here's a simple example:

from pathlib import Path
from resource import getpagesize

PAGESIZE = getpagesize()
PATH = Path('/proc/self/statm')


def get_resident_set_size() -> int:
    """Return the current resident set size in bytes."""
    # statm columns are: size resident shared text lib data dt
    statm = PATH.read_text()
    fields = statm.split()
    return int(fields[1]) * PAGESIZE


data = []
start_memory = get_resident_set_size()
for _ in range(10):
    data.append('X' * 100000)
    print(get_resident_set_size() - start_memory)

That produces a list that looks something like this:

0
0
368640
368640
368640
638976
638976
909312
909312
909312

You can see that it jumps by about 300,000 bytes after roughly 3 allocations of 100,000 bytes.

How to change the height of a <br>?

So, peeps above have got basically a similar answer, but here it is very succinctly. Works in Opera, Chrome, Safari & Firefox, most likely IE too?

br {
            display: block; /* makes it have a width */
            content: ""; /* clears default height */
            margin-top: 0; /* change this to whatever height you want it */
}

How to print the full NumPy array, without truncation?

Temporary setting

If you use NumPy 1.15 (released 2018-07-23) or newer, you can use the printoptions context manager:

with numpy.printoptions(threshold=numpy.inf):
    print(arr)

(of course, replace numpy by np if that's how you imported numpy)

The use of a context manager (the with-block) ensures that after the context manager is finished, the print options will revert to whatever they were before the block started. It ensures the setting is temporary, and only applied to code within the block.

See numpy.printoptions documentation for details on the context manager and what other arguments it supports.

What does a question mark represent in SQL queries?

The ? is an unnamed parameter which can be filled in by a program running the query to avoid SQL injection.

Integer.toString(int i) vs String.valueOf(int i)

toString()

  1. is present in Object class, generally overrided in derived class
  2. typecast to appropriate class is necessary to call toString() method.

valueOf()

  1. Overloaded static method present in String class.
  2. handles primitive types as well as object types.

    Integer a = null;
    System.out.println(Integer.toString()) ; NUll pointer exception
    System.out.println(String.valueOf() ; give NULL as value
    

check this link its very good. http://code4reference.com/2013/06/which-one-is-better-valueof-or-tostring/

Interop type cannot be embedded

Expanding on Jon's correct answer.

The problem here is that your are combining the new "Embed Interop Types" (or NoPIA) feature with use of a class type. The "Embed Interop Types" feature works by essentially statically linking in all of the types from a PIA (Primary Interop Assembly) into the referencing assembly removing the overhead of deploying it.

This feature works great for most types in a PIA but it does have restrictions. One of them is that you cannot embed classes (it's a servicing issue). Misha has a detailed blog article on why this is not allowed

Test if a property is available on a dynamic variable

As ExpandoObject inherits the IDictionary<string, object> you can use the following check

dynamic myVariable = GetDataThatLooksVerySimilarButNotTheSame();

if (((IDictionary<string, object>)myVariable).ContainsKey("MyProperty"))    
//Do stuff

You can make a utility method to perform this check, that will make the code much cleaner and re-usable

Plugin org.apache.maven.plugins:maven-compiler-plugin or one of its dependencies could not be resolved

Have you tried to remove the proxy username and password? A similar poster encountered that issue:

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

Failing that I found the following worked:

  1. Delete project in Eclipse (but do not delete the contents on disk)
  2. Delete all files in your Maven repository
  3. Re-download all Maven dependencies:

mvn dependency:resolve

  1. Start up Eclipse
  2. Ensure that Eclipse is configured to use your external Maven installation (Window->Preferences->Maven->Installations)
  3. Re-import the existing project(s) into Eclipse
  4. Ensure that there are no Maven Eclipse plugin errors on the final screen of the project import

css divide width 100% to 3 column

Just in case someone is still looking for the answer,

let the browser take care of that. Try this:

  • display: table on the container element.
  • display: table-cell on the child elements.

The browser will evenly divide it whether you have 3 or 10 columns.

EDIT

the container element should also have: table-layout: fixed otherwise the browser will determine the width of each element (most of the time not that bad).

How to display an image from a path in asp.net MVC 4 and Razor view?

you can also try with this answer :

 <img src="~/Content/img/@Html.DisplayFor(model =>model.ImagePath)" style="height:200px;width:200px;"/>