Programs & Examples On #Section508

Section 508 refers to the amendment of the United States of America's Rehabilitation Act of 1973, which requires US Federal agencies to make their electronic and information technology accessible to people with disabilities.

Using "label for" on radio buttons

(Firstly read the other answers which has explained the for in the <label></label> tags. Well, both the tops answers are correct, but for my challenge, it was when you have several radio boxes, you should select for them a common name like name="r1" but with different ids id="r1_1" ... id="r1_2"

So this way the answer is more clear and removes the conflicts between name and ids as well.

You need different ids for different options of the radio box.

_x000D_
_x000D_
<input type="radio" name="r1" id="r1_1" />_x000D_
_x000D_
       <label for="r1_1">button text one</label>_x000D_
       <br/>_x000D_
       <input type="radio" name="r1" id="r1_2" />_x000D_
_x000D_
       <label for="r1_2">button text two</label>_x000D_
       <br/>_x000D_
       <input type="radio" name="r1" id="r1_3" />_x000D_
_x000D_
       <label for="r1_3">button text three</label>
_x000D_
_x000D_
_x000D_

Express.js req.body undefined

In case if you post SOAP message you need to use raw body parser:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.raw({ type: 'text/xml' }));

How to count the frequency of the elements in an unordered list?

For the record, a functional answer:

>>> L = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>> import functools
>>> >>> functools.reduce(lambda acc, e: [v+(i==e) for i, v in enumerate(acc,1)] if e<=len(acc) else acc+[0 for _ in range(e-len(acc)-1)]+[1], L, [])
[4, 4, 2, 1, 2]

It's cleaner if you count zeroes too:

>>> functools.reduce(lambda acc, e: [v+(i==e) for i, v in enumerate(acc)] if e<len(acc) else acc+[0 for _ in range(e-len(acc))]+[1], L, [])
[0, 4, 4, 2, 1, 2]

An explanation:

  • we start with an empty acc list;
  • if the next element e of L is lower than the size of acc, we just update this element: v+(i==e) means v+1 if the index i of acc is the current element e, otherwise the previous value v;
  • if the next element e of L is greater or equals to the size of acc, we have to expand acc to host the new 1.

The elements do not have to be sorted (itertools.groupby). You'll get weird results if you have negative numbers.

Where does Internet Explorer store saved passwords?

Short answer: in the Vault. Since Windows 7, a Vault was created for storing any sensitive data among it the credentials of Internet Explorer. The Vault is in fact a LocalSystem service - vaultsvc.dll.

Long answer: Internet Explorer allows two methods of credentials storage: web sites credentials (for example: your Facebook user and password) and autocomplete data. Since version 10, instead of using the Registry a new term was introduced: Windows Vault. Windows Vault is the default storage vault for the credential manager information.

You need to check which OS is running. If its Windows 8 or greater, you call VaultGetItemW8. If its isn't, you call VaultGetItemW7.

To use the "Vault", you load a DLL named "vaultcli.dll" and access its functions as needed.

A typical C++ code will be:

hVaultLib = LoadLibrary(L"vaultcli.dll");

if (hVaultLib != NULL) 
{
    pVaultEnumerateItems = (VaultEnumerateItems)GetProcAddress(hVaultLib, "VaultEnumerateItems");
    pVaultEnumerateVaults = (VaultEnumerateVaults)GetProcAddress(hVaultLib, "VaultEnumerateVaults");
    pVaultFree = (VaultFree)GetProcAddress(hVaultLib, "VaultFree");
    pVaultGetItemW7 = (VaultGetItemW7)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultGetItemW8 = (VaultGetItemW8)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultOpenVault = (VaultOpenVault)GetProcAddress(hVaultLib, "VaultOpenVault");
    pVaultCloseVault = (VaultCloseVault)GetProcAddress(hVaultLib, "VaultCloseVault");

    bStatus = (pVaultEnumerateVaults != NULL)
        && (pVaultFree != NULL)
        && (pVaultGetItemW7 != NULL)
        && (pVaultGetItemW8 != NULL)
        && (pVaultOpenVault != NULL)
        && (pVaultCloseVault != NULL)
        && (pVaultEnumerateItems != NULL);
}

Then you enumerate all stored credentials by calling

VaultEnumerateVaults

Then you go over the results.

How can I tell how many objects I've stored in an S3 bucket?

Although this is an old question, and feedback was provided in 2015, right now it's much simpler, as S3 Web Console has enabled a "Get Size" option:

enter image description here

Which provides the following:

enter image description here

How do I get the current date and time in PHP?

The time would go by your server time. An easy workaround for this is to manually set the timezone by using date_default_timezone_set before the date() or time() functions are called to.

I'm in Melbourne, Australia so I have something like this:

date_default_timezone_set('Australia/Melbourne');

Or another example is LA - US:

date_default_timezone_set('America/Los_Angeles');

You can also see what timezone the server is currently in via:

date_default_timezone_get();

So something like:

$timezone = date_default_timezone_get();
echo "The current server timezone is: " . $timezone;

So the short answer for your question would be:

// Change the line below to your timezone!
date_default_timezone_set('Australia/Melbourne');
$date = date('m/d/Y h:i:s a', time());

Then all the times would be to the timezone you just set :)

Session variables in ASP.NET MVC

Great answers from the guys but I would caution you against always relying on the Session. It is quick and easy to do so, and of course would work but would not be great in all cicrumstances.

For example if you run into a scenario where your hosting doesn't allow session use, or if you are on a web farm, or in the example of a shared SharePoint application.

If you wanted a different solution you could look at using an IOC Container such as Castle Windsor, creating a provider class as a wrapper and then keeping one instance of your class using the per request or session lifestyle depending on your requirements.

The IOC would ensure that the same instance is returned each time.

More complicated yes, if you need a simple solution just use the session.

Here are some implementation examples below out of interest.

Using this method you could create a provider class along the lines of:

public class CustomClassProvider : ICustomClassProvider
{
    public CustomClassProvider(CustomClass customClass)
    { 
        CustomClass = customClass;
    }

    public string CustomClass { get; private set; }
}

And register it something like:

public void Install(IWindsorContainer container, IConfigurationStore store)
{
    container.Register(
            Component.For<ICustomClassProvider>().UsingFactoryMethod(
                () => new CustomClassProvider(new CustomClass())).LifestylePerWebRequest());
    }

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

eloquent laravel: How to get a row count from a ->get()

Answer has been updated

count is a Collection method. The query builder returns an array. So in order to get the count, you would just count it like you normally would with an array:

$wordCount = count($wordlist);

If you have a wordlist model, then you can use Eloquent to get a Collection and then use the Collection's count method. Example:

$wordlist = Wordlist::where('id', '<=', $correctedComparisons)->get();
$wordCount = $wordlist->count();

There is/was a discussion on having the query builder return a collection here: https://github.com/laravel/framework/issues/10478

However as of now, the query builder always returns an array.

Edit: As linked above, the query builder now returns a collection (not an array). As a result, what JP Foster was trying to do initially will work:

$wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
            ->get();
$wordCount = $wordlist->count();

However, as indicated by Leon in the comments, if all you want is the count, then querying for it directly is much faster than fetching an entire collection and then getting the count. In other words, you can do this:

// Query builder
$wordCount = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
            ->count();

// Eloquent
$wordCount = Wordlist::where('id', '<=', $correctedComparisons)->count();

Bad Request - Invalid Hostname IIS7

This solved my problem (sorry for my bad English):

  1. open cmd as administrator and run command (Without the square brackets):
    netsh http add urlacl url=http://[ip adress]:[port]/ user=everyone

  2. in documents/iisexpress/config/applicationhost.config and in your root project folder in (hidden) folder: .vs/config/applicationhost.config you need add row to "site" tag:
    <binding protocol="http" bindingInformation="*:8080:192.xxx.xxx.xxx" />

  3. open "internet information services (iis) manager"
    (to find it: in search in taskbar write "Turn Window features on or off" and open result and then check the checkbox "internet information service" and install that):

    1. in left screen click: computer-name --> Sites --> Default Web Site and
    2. then click in right screen "Binding"
    3. click Add button
    4. write what you need and press "OK".
  4. open "Windows Firewall With Advanced Security",

    1. in left screen press "Inbound Rules" and then
    2. press in right screen "New Rule..."
    3. check port and press Next,
    4. check TCP and your port and press Next,
    5. check "Allow the connection" and press Next,
    6. check all checkbox and press Next,
    7. write name and press Finish.
  5. done.

Initializing IEnumerable<string> In C#

IEnumerable is an interface, instead of looking for how to create an interface instance, create an implementation that matches the interface: create a list or an array.

IEnumerable<string> myStrings = new [] { "first item", "second item" };
IEnumerable<string> myStrings = new List<string> { "first item", "second item" };

React-Router External link

FOR V3, although it may work for V4. Going off of Eric's answer, I needed to do a little more, like handle local development where 'http' is not present on the url. I'm also redirecting to another application on the same server.

Added to router file:

import RedirectOnServer from './components/RedirectOnServer';

       <Route path="/somelocalpath"
          component={RedirectOnServer}
          target="/someexternaltargetstring like cnn.com"
        />

And the Component:

import React, { Component } from "react";

export class RedirectOnServer extends Component {

  constructor(props) {
    super();
    //if the prefix is http or https, we add nothing
    let prefix = window.location.host.startsWith("http") ? "" : "http://";
    //using host here, as I'm redirecting to another location on the same host
    this.target = prefix + window.location.host + props.route.target;
  }
  componentDidMount() {
    window.location.replace(this.target);
  }
  render(){
    return (
      <div>
        <br />
        <span>Redirecting to {this.target}</span>
      </div>
    );
  }
}

export default RedirectOnServer;

Text in Border CSS HTML

Text in Border with transparent text background

_x000D_
_x000D_
.box{
    background-image: url("https://i.stack.imgur.com/N39wV.jpg");
    width: 350px;
    padding: 10px;
}

/*begin first box*/
.first{
    width: 300px;
    height: 100px;
    margin: 10px;
    border-width: 0 2px 0 2px;
    border-color: #333;
    border-style: solid;
    position: relative;
}

.first span {
    position: absolute;
    display: flex;
    right: 0;
    left: 0;
    align-items: center;
}
.first .foo{
    top: -8px;
}
.first .bar{
    bottom: -8.5px;
}
.first span:before{
    margin-right: 15px;
}
.first span:after {
    margin-left: 15px;
}
.first span:before , .first span:after {
    content: ' ';
    height: 2px;
    background: #333;
    display: block;
    width: 50%;
}


/*begin second box*/
.second{
    width: 300px;
    height: 100px;
    margin: 10px;
    border-width: 2px 0 2px 0;
    border-color: #333;
    border-style: solid;
    position: relative;
}

.second span {
    position: absolute;
    top: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
}
.second .foo{
    left: -15px;
}
.second .bar{
    right: -15.5px;
}
.second span:before{
    margin-bottom: 15px;
}
.second span:after {
    margin-top: 15px;
}
.second span:before , .second span:after {
    content: ' ';
    width: 2px;
    background: #333;
    display: block;
    height: 50%;
}
_x000D_
<div class="box">
    <div class="first">
        <span class="foo">FOO</span>
        <span class="bar">BAR</span>
    </div>

   <br>

    <div class="second">
        <span class="foo">FOO</span>
        <span class="bar">BAR</span>
    </div>
</div>
_x000D_
_x000D_
_x000D_

What's the difference between JPA and Hibernate?

JPA is just a specification.In market there are many vendors which implements JPA. Different types of vendors implement JPA in different way. so different types of vendors provide different functionality so choose proper vendor based on your requirements.

If you are using Hibernate or any other vendors instead of JPA than you can not easily move to hibernate to EclipseLink or OpenJPA to Hibernate.But If you using JPA than you just have to change provide in persistence XML file.So migration is easily possible in JPA.

npm behind a proxy fails with status 403

On windows10, create this file. Worked for me.

enter image description here

How to show row number in Access query like ROW_NUMBER in SQL

One way to do this with MS Access is with a subquery but it does not have anything like the same functionality:

SELECT a.ID, 
       a.AText, 
       (SELECT Count(ID) 
        FROM table1 b WHERE b.ID <= a.ID 
        AND b.AText Like "*a*") AS RowNo
FROM Table1 AS a
WHERE a.AText Like "*a*"
ORDER BY a.ID;

Read from file or stdin

First, ask the program to tell you what is wrong by checking the errno, which is set on failure, such as during fseek or ftell.

Others (tonio & LatinSuD) have explained the mistake with handling stdin versus checking for a filename. Namely, first check argc (argument count) to see if there are any command line parameters specified if (argc > 1), treating - as a special case meaning stdin.

If no parameters are specified, then assume input is (going) to come from stdin, which is a stream not file, and the fseek function fails on it.

In the case of a stream, where you cannot use file-on-disk oriented library functions (i.e. fseek and ftell), you simply have to count the number of bytes read (including trailing newline characters) until receiving EOF (end-of-file).

For usage with large files you could speed it up by using fgets to a char array for more efficient reading of the bytes in a (text) file. For a binary file you need to use fopen(const char* filename, "rb") and use fread instead of fgetc/fgets.

You could also check the for feof(stdin) / ferror(stdin) when using the byte-counting method to detect any errors when reading from a stream.

The sample below should be C99 compliant and portable.

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

long getSizeOfInput(FILE *input){
   long retvalue = 0;
   int c;

   if (input != stdin) {
      if (-1 == fseek(input, 0L, SEEK_END)) {
         fprintf(stderr, "Error seek end: %s\n", strerror(errno));
         exit(EXIT_FAILURE);
      }
      if (-1 == (retvalue = ftell(input))) {
         fprintf(stderr, "ftell failed: %s\n", strerror(errno));
         exit(EXIT_FAILURE);
      }
      if (-1 == fseek(input, 0L, SEEK_SET)) {
         fprintf(stderr, "Error seek start: %s\n", strerror(errno));
         exit(EXIT_FAILURE);
      }
   } else {
      /* for stdin, we need to read in the entire stream until EOF */
      while (EOF != (c = fgetc(input))) {
         retvalue++;
      }
   }

   return retvalue;
}

int main(int argc, char **argv) {
   FILE *input;

   if (argc > 1) {
      if(!strcmp(argv[1],"-")) {
         input = stdin;
      } else {
         input = fopen(argv[1],"r");
         if (NULL == input) {
            fprintf(stderr, "Unable to open '%s': %s\n",
                  argv[1], strerror(errno));
            exit(EXIT_FAILURE);
         }
      }
   } else {
      input = stdin;
   }

   printf("Size of file: %ld\n", getSizeOfInput(input));

   return EXIT_SUCCESS;
}

How to change the height of a div dynamically based on another div using css?

The simplest way to get equal height columns, without the ugly side effects that come along with absolute positioning, is to use the display: table properties:

.div1 {
  width:300px;
  height: auto;
  background-color: grey;  
  border:1px solid;
  display: table;
}

.div2, .div3 {
  display: table-cell;
}
.div2 {
  width:150px;
  height:auto;
  background-color: #F4A460;  

}
.div3 {
  width:150px;
  height:auto;
  background-color: #FFFFE0;  
}

http://jsfiddle.net/E4Zgj/21/


Now, if your goal is to have .div2 so that it is only as tall as it needs to be to contain its content while .div3 is at least as tall as .div2 but still able to expand if its content makes it taller than .div2, then you need to use flexbox. Flexbox support isn't quite there yet (IE10, Opera, Chrome. Firefox follows an old spec, but is following the current spec soon).

.div1 {
  width:300px;
  height: auto;
  background-color: grey;  
  border:1px solid;
  display: flex;
  align-items: flex-start;
}

.div2 {
  width:150px;
  background-color: #F4A460;
}

.div3 {
  width:150px;
  background-color: #FFFFE0;
  align-self: stretch;
}

http://jsfiddle.net/E4Zgj/22/

Efficient way to add spaces between characters in a string

The most efficient way is to take input make the logic and run

so the code is like this to make your own space maker

need = input("Write a string:- ")
result = ''
for character in need:
   result = result + character + ' '
print(result)    # to rid of space after O

but if you want to use what python give then use this code

need2 = input("Write a string:- ")

print(" ".join(need2))

Where is body in a nodejs http.get response?

If you want to use .get you can do it like this

http.get(url, function(res){
    res.setEncoding('utf8');
    res.on('data', function(chunk){
        console.log(chunk);
    });

});

Importing xsd into wsdl

You have a couple of problems here.

First, the XSD has an issue where an element is both named or referenced; in your case should be referenced.

Change:

<xsd:element name="stock" ref="Stock" minOccurs="1" maxOccurs="unbounded"/> 

To:

<xsd:element name="stock" type="Stock" minOccurs="1" maxOccurs="unbounded"/> 

And:

  • Remove the declaration of the global element Stock
  • Create a complex type declaration for a type named Stock

So:

<xsd:element name="Stock">
    <xsd:complexType>

To:

<xsd:complexType name="Stock">

Make sure you fix the xml closing tags.

The second problem is that the correct way to reference an external XSD is to use XSD schema with import/include within a wsdl:types element. wsdl:import is reserved to referencing other WSDL files. More information is available by going through the WS-I specification, section WSDL and Schema Import. Based on WS-I, your case would be:

INCORRECT: (the way you showed it)

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <import namespace="http://stock.com/schemas/services/stock" location="Stock.xsd" />
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

CORRECT:

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <types>
        <schema xmlns="http://www.w3.org/2001/XMLSchema">
            <import namespace="http://stock.com/schemas/services/stock" schemaLocation="Stock.xsd" />             
        </schema>
    </types>
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

SOME processors may support both syntaxes. The XSD you put out shows issues, make sure you first validate the XSD.

It would be better if you go the WS-I way when it comes to WSDL authoring.

Other issues may be related to the use of relative vs. absolute URIs in locating external content.

Get the current cell in Excel VB

Have you tried:

For one cell:

ActiveCell.Select

For multiple selected cells:

Selection.Range

For example:

Dim rng As Range
Set rng = Range(Selection.Address)

Unix command to check the filesize

You can use:ls -lh, then you will get a list of file information

How do I redirect users after submit button click?

// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com/SpecificAction.php");

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com/SpecificAction.php";

Convert time in HH:MM:SS format to seconds only?

I think the easiest method would be to use strtotime() function:

$time = '21:30:10';
$seconds = strtotime("1970-01-01 $time UTC");
echo $seconds;

// same with objects (for php5.3+)
$time = '21:30:10';
$dt = new DateTime("1970-01-01 $time", new DateTimeZone('UTC'));
$seconds = (int)$dt->getTimestamp();
echo $seconds;

demo


Function date_parse() can also be used for parsing date and time:

$time = '21:30:10';
$parsed = date_parse($time);
$seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];

demo


If you will parse format MM:SS with strtotime() or date_parse() it will fail (date_parse() is used in strtotime() and DateTime), because when you input format like xx:yy parser assumes it is HH:MM and not MM:SS. I would suggest checking format, and prepend 00: if you only have MM:SS.

demo strtotime() demo date_parse()


If you have hours more than 24, then you can use next function (it will work for MM:SS and HH:MM:SS format):

function TimeToSec($time) {
    $sec = 0;
    foreach (array_reverse(explode(':', $time)) as $k => $v) $sec += pow(60, $k) * $v;
    return $sec;
}

demo

LEFT function in Oracle

LEFT is not a function in Oracle. This probably came from someone familiar with SQL Server:

Returns the left part of a character string with the specified number of characters.

-- Syntax for SQL Server, Azure SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse  
LEFT ( character_expression , integer_expression )  

Check difference in seconds between two times

This version always returns the number of seconds difference as a positive number (same result as @freedeveloper's solution):

var seconds = System.Math.Abs((date1 - date2).TotalSeconds);

Losing scope when using ng-include

Instead of using this as the accepted answer suggests, use $parent instead. So in your partial1.htmlyou'll have:

<form ng-submit="$parent.addLine()">
    <input type="text" ng-model="$parent.lineText" size="30" placeholder="Type your message here">
</form>

If you want to learn more about the scope in ng-include or other directives, check this out: https://github.com/angular/angular.js/wiki/Understanding-Scopes#ng-include

What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

I recommend using Spring's @ControllerAdvice to handle errors. Read this guide for a good introduction, starting at the section named "Spring Boot Error Handling". For an in-depth discussion, there's an article in the Spring.io blog that was updated on April, 2018.

A brief summary on how this works:

  • Your controller method should only return ResponseEntity<Success>. It will not be responsible for returning error or exception responses.
  • You will implement a class that handles exceptions for all controllers. This class will be annotated with @ControllerAdvice
  • This controller advice class will contain methods annotated with @ExceptionHandler
  • Each exception handler method will be configured to handle one or more exception types. These methods are where you specify the response type for errors
  • For your example, you would declare (in the controller advice class) an exception handler method for the validation error. The return type would be ResponseEntity<Error>

With this approach, you only need to implement your controller exception handling in one place for all endpoints in your API. It also makes it easy for your API to have a uniform exception response structure across all endpoints. This simplifies exception handling for your clients.

openssl s_client -cert: Proving a client certificate was sent to the server

In order to verify a client certificate is being sent to the server, you need to analyze the output from the combination of the -state and -debug flags.

First as a baseline, try running

$ openssl s_client -connect host:443 -state -debug

You'll get a ton of output, but the lines we are interested in look like this:

SSL_connect:SSLv3 read server done A
write to 0x211efb0 [0x21ced50] (12 bytes => 12 (0xC))
0000 - 16 03 01 00 07 0b 00 00-03                        .........
000c - <SPACES/NULS>
SSL_connect:SSLv3 write client certificate A

What's happening here:

  • The -state flag is responsible for displaying the end of the previous section:

    SSL_connect:SSLv3 read server done A  
    

    This is only important for helping you find your place in the output.

  • Then the -debug flag is showing the raw bytes being sent in the next step:

    write to 0x211efb0 [0x21ced50] (12 bytes => 12 (0xC))
    0000 - 16 03 01 00 07 0b 00 00-03                        .........
    000c - <SPACES/NULS>
    
  • Finally, the -state flag is once again reporting the result of the step that -debug just echoed:

    SSL_connect:SSLv3 write client certificate A
    

So in other words: s_client finished reading data sent from the server, and sent 12 bytes to the server as (what I assume is) a "no client certificate" message.


If you repeat the test, but this time include the -cert and -key flags like this:

$ openssl s_client -connect host:443 \
   -cert cert_and_key.pem \
   -key cert_and_key.pem  \
   -state -debug

your output between the "read server done" line and the "write client certificate" line will be much longer, representing the binary form of your client certificate:

SSL_connect:SSLv3 read server done A
write to 0x7bd970 [0x86d890] (1576 bytes => 1576 (0x628))
0000 - 16 03 01 06 23 0b 00 06-1f 00 06 1c 00 06 19 31   ....#..........1
(*SNIP*)
0620 - 95 ca 5e f4 2f 6c 43 11-                          ..^%/lC.
SSL_connect:SSLv3 write client certificate A

The 1576 bytes is an excellent indication on its own that the cert was transmitted, but on top of that, the right-hand column will show parts of the certificate that are human-readable: You should be able to recognize the CN and issuer strings of your cert in there.

Unsupported operation :not writeable python

You open the variable "file" as a read only then attempt to write to it:

file = open('ValidEmails.txt','r')

Instead, use the 'w' flag.

file = open('ValidEmails.txt','w')
...
file.write(email)

What are the default access modifiers in C#?

The default access for everything in C# is "the most restricted access you could declare for that member".

So for example:

namespace MyCompany
{
    class Outer
    {
        void Foo() {}
        class Inner {}
    }
}

is equivalent to

namespace MyCompany
{
    internal class Outer
    {
        private void Foo() {}
        private class Inner {}
    }
}

The one sort of exception to this is making one part of a property (usually the setter) more restricted than the declared accessibility of the property itself:

public string Name
{
    get { ... }
    private set { ... } // This isn't the default, have to do it explicitly
}

This is what the C# 3.0 specification has to say (section 3.5.1):

Depending on the context in which a member declaration takes place, only certain types of declared accessibility are permitted. Furthermore, when a member declaration does not include any access modifiers, the context in which the declaration takes place determines the default declared accessibility.

  • Namespaces implicitly have public declared accessibility. No access modifiers are allowed on namespace declarations.
  • Types declared in compilation units or namespaces can have public or internal declared accessibility and default to internal declared accessibility.
  • Class members can have any of the five kinds of declared accessibility and default to private declared accessibility. (Note that a type declared as a member of a class can have any of the five kinds of declared accessibility, whereas a type declared as a member of a namespace can have only public or internal declared accessibility.)
  • Struct members can have public, internal, or private declared accessibility and default to private declared accessibility because structs are implicitly sealed. Struct members introduced in a struct (that is, not inherited by that struct) cannot have protected or protected internal declared accessibility. (Note that a type declared as a member of a struct can have public, internal, or private declared accessibility, whereas a type declared as a member of a namespace can have only public or internal declared accessibility.)
  • Interface members implicitly have public declared accessibility. No access modifiers are allowed on interface member declarations.
  • Enumeration members implicitly have public declared accessibility. No access modifiers are allowed on enumeration member declarations.

(Note that nested types would come under the "class members" or "struct members" parts - and therefore default to private visibility.)

'ssh-keygen' is not recognized as an internal or external command

I think you can add the location of the file ssh-keygen.exe in the PATH environment variable. Follow the steps: Go to My Computer->Right click->Properties->Advanced System Settings->Click Environmental Variables. Now click PATH and then click EDIT. In the variable value field, go to the end and append ';C:\path\to\msysgit1.7.11\bin\ssh-keygen.exe' (without quotes)

Retrieve list of tasks in a queue in Celery

I think the only way to get the tasks that are waiting is to keep a list of tasks you started and let the task remove itself from the list when it's started.

With rabbitmqctl and list_queues you can get an overview of how many tasks are waiting, but not the tasks itself: http://www.rabbitmq.com/man/rabbitmqctl.1.man.html

If what you want includes the task being processed, but are not finished yet, you can keep a list of you tasks and check their states:

from tasks import add
result = add.delay(4, 4)

result.ready() # True if finished

Or you let Celery store the results with CELERY_RESULT_BACKEND and check which of your tasks are not in there.

Compare dates in MySQL

I got the answer.

Here is the code:

SELECT * FROM table
WHERE STR_TO_DATE(column, '%d/%m/%Y')
  BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
    AND STR_TO_DATE('07/10/15', '%d/%m/%Y')

MySQL Sum() multiple columns

//Mysql sum of multiple rows Hi Here is the simple way to do sum of columns

SELECT sum(IF(day_1 = 1,1,0)+IF(day_3 = 1,1,0)++IF(day_4 = 1,1,0)) from attendence WHERE class_period_id='1' and student_id='1'

Get to UIViewController from UIView?

Swift 4 version

extension UIView {
var parentViewController: UIViewController? {
    var parentResponder: UIResponder? = self
    while parentResponder != nil {
        parentResponder = parentResponder!.next
        if let viewController = parentResponder as? UIViewController {
            return viewController
        }
    }
    return nil
}

Usage example

 if let parent = self.view.parentViewController{

 }

Bi-directional Map in Java?

Use Google's BiMap

It is more convenient.

How can I make my layout scroll both horizontally and vertically?

its too late but i hope your issue will be solve quickly with this code. nothing to do more just put your code in below scrollview.

<HorizontalScrollView
        android:id="@+id/scrollView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

      <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            //xml code
      </ScrollView>
</HorizontalScrollView>

How to convert map to url query string?

I think this is better for memory usage and performance, and I want to send just the property name when the value is null.

public static String toUrlEncode(Map<String, Object> map) {
    StringBuilder sb = new StringBuilder();
    map.entrySet().stream()
            .forEach(entry
                    -> (entry.getValue() == null
                    ? sb.append(entry.getKey())
                    : sb.append(entry.getKey())
                            .append('=')
                            .append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8)))
                    .append('&')
            );
    sb.delete(sb.length() - 1, sb.length());
    return sb.toString();
}

How to justify navbar-nav in Bootstrap 3

To justify the bootstrap 3 navbar-nav justify menu to 100% width you can use this code:

@media (min-width: 768px){
    .navbar-nav {
        margin: 0 auto;
        display: table;
        table-layout: auto;
        float: none;
        width: 100%;
    }
    .navbar-nav>li {
        display: table-cell;
        float: none;
        text-align: center;
    }
} 

How to sort an array in descending order in Ruby

You could do:

a.sort{|a,b| b[:bar] <=> a[:bar]}

Extract XML Value in bash script

XMLStarlet or another XPath engine is the correct tool for this job.

For instance, with data.xml containing the following:

<root>
  <item> 
    <title>15:54:57 - George:</title>
    <description>Diane DeConn? You saw Diane DeConn!</description> 
  </item> 
  <item> 
    <title>15:55:17 - Jerry:</title> 
    <description>Something huh?</description>
  </item>
</root>

...you can extract only the first title with the following:

xmlstarlet sel -t -m '//title[1]' -v . -n <data.xml

Trying to use sed for this job is troublesome. For instance, the regex-based approaches won't work if the title has attributes; won't handle CDATA sections; won't correctly recognize namespace mappings; can't determine whether a portion of the XML documented is commented out; won't unescape attribute references (such as changing Brewster &amp; Jobs to Brewster & Jobs), and so forth.

Moving matplotlib legend outside of the axis makes it cutoff by the figure box

Sorry EMS, but I actually just got another response from the matplotlib mailling list (Thanks goes out to Benjamin Root).

The code I am looking for is adjusting the savefig call to:

fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight')
#Note that the bbox_extra_artists must be an iterable

This is apparently similar to calling tight_layout, but instead you allow savefig to consider extra artists in the calculation. This did in fact resize the figure box as desired.

import matplotlib.pyplot as plt
import numpy as np

plt.gcf().clear()
x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')
ax.plot(x, np.arctan(x), label='Inverse tan')
handles, labels = ax.get_legend_handles_labels()
lgd = ax.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5,-0.1))
text = ax.text(-0.2,1.05, "Aribitrary text", transform=ax.transAxes)
ax.set_title("Trigonometry")
ax.grid('on')
fig.savefig('samplefigure', bbox_extra_artists=(lgd,text), bbox_inches='tight')

This produces:

[edit] The intent of this question was to completely avoid the use of arbitrary coordinate placements of arbitrary text as was the traditional solution to these problems. Despite this, numerous edits recently have insisted on putting these in, often in ways that led to the code raising an error. I have now fixed the issues and tidied the arbitrary text to show how these are also considered within the bbox_extra_artists algorithm.

Hamcrest compare collections

To complement @Joe's answer:

Hamcrest provides you with three main methods to match a list:

contains Checks for matching all the elements taking in count the order, if the list has more or less elements, it will fail

containsInAnyOrder Checks for matching all the elements and it doesn't matter the order, if the list has more or less elements, will fail

hasItems Checks just for the specified objects it doesn't matter if the list has more

hasItem Checks just for one object it doesn't matter if the list has more

All of them can receive a list of objects and use equals method for comparation or can be mixed with other matchers like @borjab mentioned:

assertThat(myList , contains(allOf(hasProperty("id", is(7L)), 
                                   hasProperty("name", is("testName1")),
                                   hasProperty("description", is("testDesc1"))),
                             allOf(hasProperty("id", is(11L)), 
                                   hasProperty("name", is("testName2")),
                                   hasProperty("description", is("testDesc2")))));

http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#contains(E...) http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#containsInAnyOrder(java.util.Collection) http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#hasItems(T...)

babel-loader jsx SyntaxError: Unexpected token

I ran into a similar issue when migrating from babel 5 to babel 6.

I was just running babel to compile the src to lib folder babel src --out-dir lib

I will share my setup for babel 6:

Ensure you have the following babel 6 devDependencies installed

"babel-core": "^6.7.6",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-0": "^6.5.0"

Add your .babelrc file to the project:

{
  "presets": ["es2015", "stage-0", "react"]
}

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

I found this brilliant solution here, it uses the simple logic NAN!=NAN. https://www.codespeedy.com/check-if-a-given-string-is-nan-in-python/

Using above example you can simply do the following. This should work on different type of objects as it simply utilize the fact that NAN is not equal to NAN.

 import numpy as np
 s = pd.Series(['apple', np.nan, 'banana'])
 s.apply(lambda x: x!=x)
 out[252]
 0    False
 1     True
 2    False
 dtype: bool

Browser: Identifier X has already been declared

The problem solved when I don't use any declaration like var, let or const

EditText request focus

youredittext.requestFocus() call it from activity

oncreate();

and use the above code there

C# Switch-case string starting with

If all the cases have the same length you can use
switch (mystring.SubString(0,Math.Min(len, mystring.Length))).
Another option is to have a function that will return categoryId based on the string and switch on the id.

What are the benefits of using C# vs F# or F# vs C#?

One of the aspects of .NET I like the most are generics. Even if you write procedural code in F#, you will still benefit from type inference. It makes writing generic code easy.

In C#, you write concrete code by default, and you have to put in some extra work to write generic code.

In F#, you write generic code by default. After spending over a year of programming in both F# and C#, I find that library code I write in F# is both more concise and more generic than the code I write in C#, and is therefore also more reusable. I miss many opportunities to write generic code in C#, probably because I'm blinded by the mandatory type annotations.

There are however situations where using C# is preferable, depending on one's taste and programming style.

  • C# does not impose an order of declaration among types, and it's not sensitive to the order in which files are compiled.
  • C# has some implicit conversions that F# cannot afford because of type inference.

Is it possible to set async:false to $.getJSON call

You need to make the call using $.ajax() to it synchronously, like this:

$.ajax({
  url: myUrl,
  dataType: 'json',
  async: false,
  data: myData,
  success: function(data) {
    //stuff
    //...
  }
});

This would match currently using $.getJSON() like this:

$.getJSON(myUrl, myData, function(data) { 
  //stuff
  //...
});

How do I make a checkbox required on an ASP.NET form?

Scott's answer will work for classes of checkboxes. If you want individual checkboxes, you have to be a little sneakier. If you're just doing one box, it's better to do it with IDs. This example does it by specific check boxes and doesn't require jQuery. It's also a nice little example of how you can get those pesky control IDs into your Javascript.

The .ascx:

<script type="text/javascript">

    function checkAgreement(source, args)
    {                
        var elem = document.getElementById('<%= chkAgree.ClientID %>');
        if (elem.checked)
        {
            args.IsValid = true;
        }
        else
        {        
            args.IsValid = false;
        }
    }

    function checkAge(source, args)
    {
        var elem = document.getElementById('<%= chkAge.ClientID %>');
        if (elem.checked)
        {
            args.IsValid = true;
        }
        else
        {
            args.IsValid = false;
        }    
    }

</script>

<asp:CheckBox ID="chkAgree" runat="server" />
<asp:Label AssociatedControlID="chkAgree" runat="server">I agree to the</asp:Label>
<asp:HyperLink ID="lnkTerms" runat="server">Terms & Conditions</asp:HyperLink>
<asp:Label AssociatedControlID="chkAgree" runat="server">.</asp:Label>
<br />

<asp:CustomValidator ID="chkAgreeValidator" runat="server" Display="Dynamic"
    ClientValidationFunction="checkAgreement">
    You must agree to the terms and conditions.
    </asp:CustomValidator>

<asp:CheckBox ID="chkAge" runat="server" />
<asp:Label AssociatedControlID="chkAge" runat="server">I certify that I am at least 18 years of age.</asp:Label>        
<asp:CustomValidator ID="chkAgeValidator" runat="server" Display="Dynamic"
    ClientValidationFunction="checkAge">
    You must be 18 years or older to continue.
    </asp:CustomValidator>

And the codebehind:

Protected Sub chkAgreeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgreeValidator.ServerValidate
    e.IsValid = chkAgree.Checked
End Sub

Protected Sub chkAgeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgeValidator.ServerValidate
    e.IsValid = chkAge.Checked
End Sub

Why is this printing 'None' in the output?

Because of double print function. I suggest you to use return instead of print inside the function definition.

def lyrics():
    return "The very first line"
print(lyrics())

OR

def lyrics():
    print("The very first line")
lyrics()

How do I test if a recordSet is empty? isNull?

If temp_rst1.BOF and temp_rst1.EOF then the recordset is empty. This will always be true for an empty recordset, linked or local.

python JSON object must be str, bytes or bytearray, not 'dict

import json
data = json.load(open('/Users/laxmanjeergal/Desktop/json.json'))
jtopy=json.dumps(data) #json.dumps take a dictionary as input and returns a string as output.
dict_json=json.loads(jtopy) # json.loads take a string as input and returns a dictionary as output.
print(dict_json["shipments"])

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

Another solution is mentioned in MDN's parseFloat page

It provides a filter function to do strict parsing

var filterFloat = function (value) {
    if(/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/
      .test(value))
      return Number(value);
  return NaN;
}


console.log(filterFloat('421'));               // 421
console.log(filterFloat('-421'));              // -421
console.log(filterFloat('+421'));              // 421
console.log(filterFloat('Infinity'));          // Infinity
console.log(filterFloat('1.61803398875'));     // 1.61803398875
console.log(filterFloat('421e+0'));            // NaN
console.log(filterFloat('421hop'));            // NaN
console.log(filterFloat('hop1.61803398875'));  // NaN

And then you can use isNaN to check if it is NaN

Java null check why use == instead of .equals()

here is an example where str != null but str.equals(null) when using org.json

 JSONObject jsonObj = new JSONObject("{field :null}");
 Object field = jsonObj.get("field");
 System.out.println(field != null);        // => true
 System.out.println( field.equals(null)); //=> true
 System.out.println( field.getClass());  // => org.json.JSONObject$Null




EDIT: here is the org.json.JSONObject$Null class:

/**
 * JSONObject.NULL is equivalent to the value that JavaScript calls null,
 * whilst Java's null is equivalent to the value that JavaScript calls
 * undefined.
 */
private static final class Null {

    /**
     * A Null object is equal to the null value and to itself.
     *
     * @param object
     *            An object to test for nullness.
     * @return true if the object parameter is the JSONObject.NULL object or
     *         null.
     */
    @Override
    public boolean equals(Object object) {
        return object == null || object == this;
    }  
}

How to set the Android progressbar's height?

As mentioned in other answers, it looks like you are setting the style of your progress bar to use Holo.Light:

style="@android:style/Widget.Holo.Light.ProgressBar.Horizontal"

If this is running on your phone, its probably a 3.0+ device. However your emulator looks like its using a "default" progress bar.

style="@android:style/Widget.ProgressBar.Horizontal"

Perhaps you changed the style to the "default" progress bar in between creating the screen captures? Unfortunately 2.x devices won't automatically default back to the "default" progress bar if your projects uses a Holo.Light progress bar. It will just crash.

If you truly are using the default progress bar then setting the max/min height as suggested will work fine. However, if you are using the Holo.Light (or Holo) bar then setting the max/min height will not work. Here is a sample output from setting max/min height to 25 and 100 dip:

max/min set to 25 dip: 25 dip height progress bar

max/min set to 100 dip: 100 dip height progress bar

You can see that the underlying drawable (progress_primary_holo_light.9.png) isn't scaling as you'd expect. The reason for this is that the 9-patch border is only scaling the top and bottom few pixels:

9-patch

The horizontal area bordered by the single-pixel, black border (green arrows) is the part that gets stretched when Android needs to resize the .png vertically. The area in between the two red arrows won't get stretched vertically.

The best solution to fix this is to change the 9patch .png's to stretch the bar and not the "canvas area" and then create a custom progress bar xml to use these 9patches. Similarly described here: https://stackoverflow.com/a/18832349

Here is my implementation for just a non-indeterminant Holo.Light ProgressBar. You'll have to add your own 9-patches for indeterminant and Holo ProgressBars. Ideally I should have removed the canvas area entirely. Instead I left it but set the "bar" area stretchable. https://github.com/tir38/ScalingHoloProgressBar

Cast int to varchar

I solved a problem to comparing a integer Column x a varchar column with

where CAST(Column_name AS CHAR CHARACTER SET latin1 ) collate latin1_general_ci = varchar_column_name

ImportError: No module named PyQt4.QtCore

You don't have g++ installed, simple way to have all the needed build tools is to install the package build-essential:

sudo apt-get install build-essential

, or just the g++ package:

sudo apt-get install g++

Stack smashing detected

Stack corruptions ususally caused by buffer overflows. You can defend against them by programming defensively.

Whenever you access an array, put an assert before it to ensure the access is not out of bounds. For example:

assert(i + 1 < N);
assert(i < N);
a[i + 1] = a[i];

This makes you think about array bounds and also makes you think about adding tests to trigger them if possible. If some of these asserts can fail during normal use turn them into a regular if.

Pycharm does not show plot

In non-interactive env, we have to use plt.show(block=True)

Better techniques for trimming leading zeros in SQL Server?

This might help

SELECT ABS(column_name) FROM [db].[schema].[table]

Connect to Amazon EC2 file directory using Filezilla and SFTP

If anyone is following all the steps and having no success, make sure that you are using the correct user. I was attempting to use "ec2-user" but I needed to use "ubuntu."

How/When does Execute Shell mark a build as failure in Jenkins?

In Jenkins ver. 1.635, it is impossible to show a native environment variable like this:

$BUILD_NUMBER or ${BUILD_NUMBER}

In this case, you have to set it in an other variable.

set BUILDNO = $BUILD_NUMBER
$BUILDNO

HTML+CSS: How to force div contents to stay in one line?

Try setting a height so the block cannot grow to accommodate your text, and keep the overflow: hidden parameter

EDIT: Here is an example of what you might like if you need to display 2 lines high:

div {
    border: 1px solid black;
    width: 70px;
    height: 2.2em;
    overflow: hidden;
}

jQuery: count number of rows in a table

var trLength = jQuery('#tablebodyID >tr').length;

Postgresql -bash: psql: command not found

In case you are running it on Fedora or CentOS, this is what worked for me (PostgreSQL 9.6):

In terminal:

$ sudo visudo -f /etc/sudoers

modify the following text from:

Defaults    secure_path = /sbin:/bin:/usr/sbin:/usr/bin

to

Defaults    secure_path = /sbin:/bin:/usr/sbin:/usr/bin:/usr/pgsql-9.6/bin

exit, then:

$ printenv PATH

$ sudo su postgres

$ psql

To exit postgreSQL terminal, you need to digit:

$ \q

Source: https://serverfault.com/questions/541847/why-doesnt-sudo-know-where-psql-is#comment623883_541880

What are all codecs and formats supported by FFmpeg?

ffmpeg -codecs

should give you all the info about the codecs available.

You will see some letters next to the codecs:

Codecs:
 D..... = Decoding supported
 .E.... = Encoding supported
 ..V... = Video codec
 ..A... = Audio codec
 ..S... = Subtitle codec
 ...I.. = Intra frame-only codec
 ....L. = Lossy compression
 .....S = Lossless compression

How to use not contains() in xpath?

XPath queries are case sensitive. Having looked at your example (which, by the way, is awesome, nobody seems to provide examples anymore!), I can get the result you want just by changing "business", to "Business"

//production[not(contains(category,'Business'))]

I have tested this by opening the XML file in Chrome, and using the Developer tools to execute that XPath queries, and it gave me just the Film category back.

Is there a maximum number you can set Xmx to when trying to increase jvm memory?

I think that it's around 2GB. While the answer by Pete Kirkham is very interesting and probably holds truth, I have allocated upwards of 3GB without error, however it did not use 3GB in practice. That might explain why you were able to allocate 2.5 GB on 2GB RAM with no swap space. In practice, it wasn't using 2.5GB.

How to find a hash key containing a matching value

Heres an easy way to do find the keys of a given value:

    clients = {
      "yellow"=>{"client_id"=>"2178"}, 
      "orange"=>{"client_id"=>"2180"}, 
      "red"=>{"client_id"=>"2179"}, 
      "blue"=>{"client_id"=>"2181"}
    }

    p clients.rassoc("client_id"=>"2180")

...and to find the value of a given key:

    p clients.assoc("orange") 

it will give you the key-value pair.

Only numbers. Input number in React

Maybe, it will be helpful for someone
Recently I used this solution for my App
I am not sure that is a correct solution but it works fine.

this.state = {
    inputValue: "",
    isInputNotValid: false
}

handleInputValue = (evt) => {
    this.validationField(evt, "isInputNotValid", "inputValue");
}

validationField = (evt, isFieldNotValid, fieldValue ) => {
   if (evt.target.value && !isNaN(evt.target.value)) {
        this.setState({ 
            [isFieldNotValid]: false,
            [fieldValue]: evt.target.value,
        });
    } else {
        this.setState({ 
            [isFieldNotValid]: true,
            [fieldValue]: "",
        });
    }
}

<input className={this.state.isInputNotValid ? "error" : null} type="text" onChange="this.handleInputValue" />

The main idea, that state won't update till the condition isn't true and value will be empty.
Don't need to use onKeyPress, Down etc.,
also if you use these methods they aren't working on touch devices

/exclude in xcopy just for a file type

For excluding multiple file types, you can use '+' to concatenate other lists. For example:

xcopy /r /d /i /s /y /exclude:excludedfileslist1.txt+excludedfileslist2.txt C:\dev\apan C:\web\apan

Source: http://www.tech-recipes.com/rx/2682/xcopy_command_using_the_exclude_flag/

When and why do I need to use cin.ignore() in C++?

Ignore function is used to skip(discard/throw away) characters in the input stream. Ignore file is associated with the file istream. Consider the function below ex: cin.ignore(120,'/n'); the particular function skips the next 120 input character or to skip the characters until a newline character is read.

How do I convert from stringstream to string in C++?

From memory, you call stringstream::str() to get the std::string value out.

Angular2 - Focusing a textbox on component load

I didn't have much luck with many of these solutions on all browsers. This is the solution that worked for me.

For router changes:

router.events.subscribe((val) => {
    setTimeout(() => {
        if (this.searchElement) {
            this.searchElement.nativeElement.focus();
        }
    }, 1);
})

Then ngAfterViewInit() for the onload scenario.

cannot make a static reference to the non-static field

the lines

account.withdraw(balance, 2500);
account.deposit(balance, 3000);

you might want to make withdraw and deposit non-static and let it modify the balance

public void withdraw(double withdrawAmount) {
    balance = balance - withdrawAmount;
}

public void deposit(double depositAmount) {
    balance = balance + depositAmount;
}   

and remove the balance parameter from the call

What is the 'new' keyword in JavaScript?

Suppose you have this function:

var Foo = function(){
  this.A = 1;
  this.B = 2;
};

If you call this as a standalone function like so:

Foo();

Executing this function will add two properties to the window object (A and B). It adds it to the window because window is the object that called the function when you execute it like that, and this in a function is the object that called the function. In Javascript at least.

Now, call it like this with new:

var bar = new Foo();

What happens when you add new to a function call is that a new object is created (just var bar = new Object()) and that the this within the function points to the new Object you just created, instead of to the object that called the function. So bar is now an object with the properties A and B. Any function can be a constructor, it just doesn't always make sense.

How do I get the SharedPreferences from a PreferenceActivity in Android?

Declare these methods first..

public static void putPref(String key, String value, Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(key, value);
    editor.commit();
}

public static String getPref(String key, Context context) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    return preferences.getString(key, null);
}

Then call this when you want to put a pref:

putPref("myKey", "mystring", getApplicationContext());

call this when you want to get a pref:

getPref("myKey", getApplicationContext());

Or you can use this object https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo which simplifies everything even further

Example:

TinyDB tinydb = new TinyDB(context);

tinydb.putInt("clickCount", 2);
tinydb.putFloat("xPoint", 3.6f);
tinydb.putLong("userCount", 39832L);

tinydb.putString("userName", "john");
tinydb.putBoolean("isUserMale", true); 

tinydb.putList("MyUsers", mUsersArray);
tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap);

SQL Bulk Insert with FIRSTROW parameter skips the following line

Maybe check that the header has the same line-ending as the actual data rows (as specified in ROWTERMINATOR)?

Update: from MSDN:

The FIRSTROW attribute is not intended to skip column headers. Skipping headers is not supported by the BULK INSERT statement. When skipping rows, the SQL Server Database Engine looks only at the field terminators, and does not validate the data in the fields of skipped rows.

Run all SQL files in a directory

For executing every SQLfile on the same directory use the following command:

ls | awk '{print "@"$0}' > all.sql

This command will create a single SQL file with the names of every SQL file in the directory appended by "@".

After the all.sql is created simply execute all.sql with SQLPlus, this will execute every sql file in the all.sql.

How do I reset the setInterval timer?

Once you clear the interval using clearInterval you could setInterval once again. And to avoid repeating the callback externalize it as a separate function:

var ticker = function() {
    console.log('idle');
};

then:

var myTimer = window.setInterval(ticker, 4000);

then when you decide to restart:

window.clearInterval(myTimer);
myTimer = window.setInterval(ticker, 4000);

Add a new item to recyclerview programmatically?

simply add to your data structure ( mItems ) , and then notify your adapter about dataset change

private void addItem(String item) {
  mItems.add(item);
  mAdapter.notifyDataSetChanged();
}

addItem("New Item");

Value cannot be null. Parameter name: source

I had this one a while back, and the answer isn't necessarily what you'd expect. This error message often crops up when your connection string is wrong.

At a guess, you'll need something like this:

<connectionStrings>
    <add name="hublisherEntities" connectionString="Data Source=localhost;Initial Catalog=hublisher;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
        <parameters>
            <parameter value="Data Source=localhost;Initial Catalog=hublisher;Integrated Security=True" />
        </parameters>
    </defaultConnectionFactory>
</entityFramework>

What's happening is that it's looking for a data source in the wrong place; Entity Framework specifies it slightly differently. If you post your connection string and EF config then we can check.

Install mysql-python (Windows)

try running the following command:

pip install mysqlclient

Server Error in '/' Application. ASP.NET

I have the same issue, my application was running on amazon vps, lately i found that bin folder had multiple copies of dll's ... After removing those copies of dlls like entityframework(copy1).dll, errors were gone.... May be some one will get help...cheers

toBe(true) vs toBeTruthy() vs toBeTrue()

There are a lot many good answers out there, i just wanted to add a scenario where the usage of these expectations might be helpful. Using element.all(xxx), if i need to check if all elements are displayed at a single run, i can perform -

expect(element.all(xxx).isDisplayed()).toBeTruthy(); //Expectation passes
expect(element.all(xxx).isDisplayed()).toBe(true); //Expectation fails
expect(element.all(xxx).isDisplayed()).toBeTrue(); //Expectation fails

Reason being .all() returns an array of values and so all kinds of expectations(getText, isPresent, etc...) can be performed with toBeTruthy() when .all() comes into picture. Hope this helps.

Why is my asynchronous function returning Promise { <pending> } instead of a value?

The then method returns a pending promise which can be resolved asynchronously by the return value of a result handler registered in the call to then, or rejected by throwing an error inside the handler called.

So calling AuthUser will not suddenly log the user in synchronously, but returns a promise whose then registered handlers will be called after the login succeeds ( or fails). I would suggest triggering all login processing by a then clause of the login promise. E.G. using named functions to highlight the sequence of flow:

let AuthUser = data => {   // just the login promise
  return google.login(data.username, data.password);
};

AuthUser(data).then( processLogin).catch(loginFail);

function processLogin( token) {
      // do logged in stuff:
      // enable, initiate, or do things after login
}
function loginFail( err) {
      console.log("login failed: " + err);
}

Get contentEditable caret index position

As this took me forever to figure out using the new window.getSelection API I am going to share for posterity. Note that MDN suggests there is wider support for window.getSelection, however, your mileage may vary.

const getSelectionCaretAndLine = () => {
    // our editable div
    const editable = document.getElementById('editable');

    // collapse selection to end
    window.getSelection().collapseToEnd();

    const sel = window.getSelection();
    const range = sel.getRangeAt(0);

    // get anchor node if startContainer parent is editable
    let selectedNode = editable === range.startContainer.parentNode
      ? sel.anchorNode 
      : range.startContainer.parentNode;

    if (!selectedNode) {
        return {
            caret: -1,
            line: -1,
        };
    }

    // select to top of editable
    range.setStart(editable.firstChild, 0);

    // do not use 'this' sel anymore since the selection has changed
    const content = window.getSelection().toString();
    const text = JSON.stringify(content);
    const lines = (text.match(/\\n/g) || []).length + 1;

    // clear selection
    window.getSelection().collapseToEnd();

    // minus 2 because of strange text formatting
    return {
        caret: text.length - 2, 
        line: lines,
    }
} 

Here is a jsfiddle that fires on keyup. Note however, that rapid directional key presses, as well as rapid deletion seems to be skip events.

How to restart service using command prompt?

You could create a .bat-file with following content:

net stop "my service name"
net start "my service name"

Using Tempdata in ASP.NET MVC - Best practice

Please note that MVC 3 onwards the persistence behavior of TempData has changed, now the value in TempData is persisted until it is read, and not just for the next request.

The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request. https://msdn.microsoft.com/en-in/library/dd394711%28v=vs.100%29.aspx

Setting a minimum/maximum character count for any character using a regular expression

Like this: .

The . means any character except newline (which sometimes is but often isn't included, check your regex flavour).

You can rewrite your expression as ^.{1,35}$, which should match any line of length 1-35.

Can linux cat command be used for writing text to file?

I use the following code to write raw text to files, to update my CPU-settings. Hope this helps out! Script:

#!/bin/sh

cat > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor <<EOF
performance
EOF

cat > /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor <<EOF
performance
EOF

This writes the text "performance" to the two files mentioned in the script above. This example overwrite old data in files.

This code is saved as a file (cpu_update.sh) and to make it executable run:

chmod +x cpu_update.sh

After that, you can run the script with:

./cpu_update.sh

IF you do not want to overwrite the old data in the file, switch out

cat > /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor <<EOF

with

cat >> /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor <<EOF

This will append your text to the end of the file without removing what other data already is in the file.

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

I used @user2709454 approach with small improvement.

public class User {
    private Set<Role> roles;

    public void setRoles(Set<Role> roles) {
        if (this.roles == null) {
            this.roles = roles;
        } else if(this.roles != roles) { // not the same instance, in other case we can get ConcurrentModificationException from hibernate AbstractPersistentCollection
            this.roles.clear();
            if(roles != null){
                this.roles.addAll(roles);
            }
        }
    }
}

get current date with 'yyyy-MM-dd' format in Angular 4

you can try doing this.


component.ts

currentDate = new Date();

component.html

{{currentDate | date:'yyyy-MM-dd'}}

What is the difference between String and StringBuffer in Java?

A String is an immutable character array.

A StringBuffer is a mutable character array. Often converted back to String when done mutating.

Since both are an array, the maximum size for both is equal to the maximum size of an integer, which is 2^31-1 (see JavaDoc, also check out the JavaDoc for both String and StringBuffer).This is because the .length argument of an array is a primitive int. (See Arrays).

How to convert a full date to a short date in javascript?

Try this:

new Date().toLocaleFormat("%x");

What's the purpose of git-mv?

There's a niche case where git mv remains very useful: when you want to change the casing of a file name on a case-insensitive file system. Both APFS (mac) and NTFS (windows) are, by default, case-insensitive (but case-preserving).

greg.kindel mentions this in a comment on CB Bailey's answer.

Suppose you are working on a mac and have a file Mytest.txt managed by git. You want to change the file name to MyTest.txt.

You could try:

$ mv Mytest.txt MyTest.txt
overwrite MyTest.txt? (y/n [n]) y
$ git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean

Oh dear. Git doesn't acknowledge there's been any change to the file.

You could work around this with by renaming the file completely then renaming it back:

$ mv Mytest.txt temp.txt
$ git rm Mytest.txt
rm 'Mytest.txt'
$ mv temp.txt MyTest.txt
$ git add MyTest.txt 
$ git status
On branch master
Your branch is up to date with 'origin/master'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    renamed:    Mytest.txt -> MyTest.txt

Hurray!

Or you could save yourself all that bother by using git mv:

$ git mv Mytest.txt MyTest.txt
$ git status
On branch master
Your branch is up to date with 'origin/master'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    renamed:    Mytest.txt -> MyTest.txt

Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick

In the ActionListener Class you can simply add

public void actionPerformed(ActionEvent event) {
    if (event.getSource()==textField){
        textButton.doClick();
    }
    else if (event.getSource()==textButton) {
        //do something
    }
}

jQuery: Check if div with certain class name exists

You can use size(), but jQuery recommends you use length to avoid the overhead of another function call:

$('div.mydivclass').length

So:

// since length is zero, it evaluates to false
if ($('div.mydivclass').length) {

http://api.jquery.com/size/

http://api.jquery.com/length/

UPDATE

The selected answer uses a perf test, but it's slightly flawed since it is also including element selection as part of the perf, which is not what's being tested here. Here is an updated perf test:

http://jsperf.com/check-if-div-exists/3

My first run of the test shows that property retrieval is faster than index retrieval, although IMO it's pretty negligible. I still prefer using length as to me it makes more sense as to the intent of the code instead of a more terse condition.

Use underscore inside Angular controllers

I use this:

var myapp = angular.module('myApp', [])
  // allow DI for use in controllers, unit tests
  .constant('_', window._)
  // use in views, ng-repeat="x in _.range(3)"
  .run(function ($rootScope) {
     $rootScope._ = window._;
  });

See https://github.com/angular/angular.js/wiki/Understanding-Dependency-Injection about halfway for some more info on run.

How to send a header using a HTTP request through a curl call?

I've switched from curl to Httpie; the syntax looks like:

http http://myurl HeaderName:value

Why should a Java class implement comparable?

Comparable defines a natural ordering. What this means is that you're defining it when one object should be considered "less than" or "greater than".

Suppose you have a bunch of integers and you want to sort them. That's pretty easy, just put them in a sorted collection, right?

TreeSet<Integer> m = new TreeSet<Integer>(); 
m.add(1);
m.add(3);
m.add(2);
for (Integer i : m)
... // values will be sorted

But now suppose I have some custom object, where sorting makes sense to me, but is undefined. Let's say, I have data representing districts by zipcode with population density, and I want to sort them by density:

public class District {
  String zipcode; 
  Double populationDensity;
}

Now the easiest way to sort them is to define them with a natural ordering by implementing Comparable, which means there's a standard way these objects are defined to be ordered.:

public class District implements Comparable<District>{
  String zipcode; 
  Double populationDensity;
  public int compareTo(District other)
  {
    return populationDensity.compareTo(other.populationDensity);
  }
}

Note that you can do the equivalent thing by defining a comparator. The difference is that the comparator defines the ordering logic outside the object. Maybe in a separate process I need to order the same objects by zipcode - in that case the ordering isn't necessarily a property of the object, or differs from the objects natural ordering. You could use an external comparator to define a custom ordering on integers, for example by sorting them by their alphabetical value.

Basically the ordering logic has to exist somewhere. That can be -

  • in the object itself, if it's naturally comparable (extends Comparable -e.g. integers)

  • supplied in an external comparator, as in the example above.

Can't find out where does a node.js app running and can't kill it

If all those kill process commands don't work for you, my suggestion is to check if you were using any other packages to run your node process.

I had the similar issue, and it was due to I was running my node process using PM2(a NPM package). The kill [processID] command disables the process but keeps the port occupied. Hence I had to go into PM2 and dump all node process to free up the port again.

What does "hashable" mean in Python?

All the answers here have good working explanation of hashable objects in python, but I believe one needs to understand the term Hashing first.

Hashing is a concept in computer science which is used to create high performance, pseudo random access data structures where large amount of data is to be stored and accessed quickly.

For example, if you have 10,000 phone numbers, and you want to store them in an array (which is a sequential data structure that stores data in contiguous memory locations, and provides random access), but you might not have the required amount of contiguous memory locations.

So, you can instead use an array of size 100, and use a hash function to map a set of values to same indices, and these values can be stored in a linked list. This provides a performance similar to an array.

Now, a hash function can be as simple as dividing the number with the size of the array and taking the remainder as the index.

For more detail refer to https://en.wikipedia.org/wiki/Hash_function

Here is another good reference: http://interactivepython.org/runestone/static/pythonds/SortSearch/Hashing.html

Iterating a JavaScript object's properties using jQuery

Late, but can be done by using Object.keys like,

_x000D_
_x000D_
var a={key1:'value1',key2:'value2',key3:'value3',key4:'value4'},_x000D_
  ulkeys=document.getElementById('object-keys'),str='';_x000D_
var keys = Object.keys(a);_x000D_
for(i=0,l=keys.length;i<l;i++){_x000D_
   str+= '<li>'+keys[i]+' : '+a[keys[i]]+'</li>';_x000D_
}_x000D_
ulkeys.innerHTML=str;
_x000D_
<ul id="object-keys"></ul>
_x000D_
_x000D_
_x000D_

How to convert JSON to a Ruby hash

You could also use Rails' with_indifferent_access method so you could access the body with either symbols or strings.

value = '{"val":"test","val1":"test1","val2":"test2"}'
json = JSON.parse(value).with_indifferent_access

then

json[:val] #=> "test"

json["val"] #=> "test"

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here

get specific row from spark dataframe

There is a scala way (if you have a enough memory on working machine):

val arr = df.select("column").rdd.collect
println(arr(100))

If dataframe schema is unknown, and you know actual type of "column" field (for example double), than you can get arr as following:

val arr = df.select($"column".cast("Double")).as[Double].rdd.collect

webpack: Module not found: Error: Can't resolve (with relative path)

Look the path for example this import is not correct import Navbar from '@/components/Navbar.vue' should look like this ** import Navbar from './components/Navbar.vue'**

ECMAScript 6 arrow function that returns an object

You must wrap the returning object literal into parentheses. Otherwise curly braces will be considered to denote the function’s body. The following works:

p => ({ foo: 'bar' });

You don't need to wrap any other expression into parentheses:

p => 10;
p => 'foo';
p => true;
p => [1,2,3];
p => null;
p => /^foo$/;

and so on.

Reference: MDN - Returning object literals

Python Request Post with param data

Assign the response to a value and test the attributes of it. These should tell you something useful.

response = requests.post(url,params=data,headers=headers)
response.status_code
response.text
  • status_code should just reconfirm the code you were given before, of course

How to cast List<Object> to List<MyClass>

With Java 8 Streams:

Sometimes brute force casting is fine:

List<MyClass> mythings = (List<MyClass>) (Object) objects

But here's a more versatile solution:

List<Object> objects = Arrays.asList("String1", "String2");

List<String> strings = objects.stream()
                       .map(element->(String) element)
                       .collect(Collectors.toList());

There's a ton of benefits, but one is that you can cast your list more elegantly if you can't be sure what it contains:

objects.stream()
    .filter(element->element instanceof String)
    .map(element->(String)element)
    .collect(Collectors.toList());

How to remove leading and trailing whitespace in a MySQL field?

If you need to use trim in select query, you can also use regular expressions

SELECT * FROM table_name WHERE field RLIKE ' * query-string *'

return rows with field like '      query-string   '

How to add a "sleep" or "wait" to my Lua Script?

if you're using a MacBook or UNIX based system, use this:

function wait(time)
if tonumber(time) ~= nil then
os.execute("Sleep "..tonumber(time))
else
os.execute("Sleep "..tonumber("0.1"))
end
wait()

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

How to replace substrings in windows batch file

If you have Ruby for Windows,

C:\>more file
bath Abath Bbath XYZbathABC

C:\>ruby -pne "$_.gsub!(/bath/,\"hello\")" file
hello Ahello Bhello XYZhelloABC

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

If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.

Go to SearchFind in Files (Ctrl+Shift+F for the keyboard addicted) and enter:

  • Find What = (cat|town)

  • Filters = *.txt

  • Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.

  • Search mode = Regular Expression

pip not working in Python Installation in Windows 10

I had the same problem on Visual Studio Code. For various reasons several python versions are installed on my computer. I was thus able to easily solve the problem by switching python interpreter.

If like me you have several versions of python on you machine, in Visual Studio Code, you can easily change the interpreter by clicking on the bottom left corner where it says Python...

enter image description here

Is it possible to GROUP BY multiple columns using MySQL?

group by fV.tier_id, f.form_template_id

ADB not recognising Nexus 4 under Windows 7

I had the same problem, but I didn't want to change to PTP mode. This is how I fixed it with MTP still enabled.

  1. Uninstalled Google USB Driver from Eclipse in the Android SDK Manager.
  2. Uninstalled the driver from Device Manager - click box for "delete driver from my computer"
  3. Unplugged and re-plugged my phone into the computer.
  4. Windows "improperly" installed drivers for the Nexus 4.
  5. The Nexus 4 was now showing up in My Computer like a drive.
  6. Reinstall Google USB Driver in SDK Manager.
  7. Update Nexus 4 driver in Device Manager.
  8. Everything works.

How do I select a MySQL database through CLI?

Hope this helps.

use [YOUR_DB_NAME];

How to run a function in jquery

Alternatively (I'd say preferably), you can do it like this:

$(function () {
  $("div.class, div.secondclass").click(function(){
    //Doo something
  });
});

jquery beforeunload when closing (not leaving) the page?

As indicated here https://stackoverflow.com/a/1632004/330867, you can implement it by "filtering" what is originating the exit of this page.

As mentionned in the comments, here's a new version of the code in the other question, which also include the ajax request you make in your question :

var canExit = true;

// For every function that will call an ajax query, you need to set the var "canExit" to false, then set it to false once the ajax is finished.

function checkCart() {
  canExit = false;
  $.ajax({
    url : 'index.php?route=module/cart/check',
    type : 'POST',
    dataType : 'json',
    success : function (result) {
       if (result) {
        canExit = true;
       }
    }
  })
}

$(document).on('click', 'a', function() {canExit = true;}); // can exit if it's a link
$(window).on('beforeunload', function() {
    if (canExit) return null; // null will allow exit without a question
    // Else, just return the message you want to display
    return "Do you really want to close?";
});

Important: You shouldn't have a global variable defined (here canExit), this is here for simpler version.

Note that you can't override completely the confirm message (at least in chrome). The message you return will only be prepended to the one given by Chrome. Here's the reason : How can I override the OnBeforeUnload dialog and replace it with my own?

Referring to the null object in Python

Per Truth value testing, 'None' directly tests as FALSE, so the simplest expression will suffice:

if not foo:

How can I make git show a list of the files that are being tracked?

If you want to list all the files currently being tracked under the branch master, you could use this command:

git ls-tree -r master --name-only

If you want a list of files that ever existed (i.e. including deleted files):

git log --pretty=format: --name-only --diff-filter=A | sort - | sed '/^$/d'

How to link to a named anchor in Multimarkdown?

Here is my solution (derived from SaraubhM's answer)

**Jump To**: [Hotkeys & Markers](#hotkeys-markers) / [Radii](#radii) / [Route Wizard 2.0](#route-wizard-2-0)

Which gives you:

Jump To: Hotkeys & Markers / Radii / Route Wizard 2.0

Note the changes from and . to - and also the loss of the & in the links.

What's the difference between git reset --mixed, --soft, and --hard?

--mixed vs --soft vs --hard:

--mixed:

   Delete changes from the local repository and staging area.

   It won't touch the working directory.

   Possible to revert back changes by using the following commands.

     - git add

     - git commit

   Working tree won't be clean.

--soft:

    Deleted changes only from the local repository.

    It won't touch the staging area and working directory.

    Possible to revert back changes by using the following command.

     - git commit.

    Working tree won't be clean

--hard:

    Deleted changes from everywhere.

    Not possible to revert changes.

    The working tree will be clean.

NOTE: If the commits are confirmed to the local repository and to discard those commits we can use:

 `git reset command`.

But if the commits are confirmed to the remote repository then not recommended to use the reset command and we have to use the revert command to discard the remote commits.

How to script FTP upload and download?

I've done this with PowerShell:

function DownloadFromFtp($destination, $ftp_uri, $user, $pass){
    $dirs = GetDirecoryTree $ftp_uri $user $pass

    foreach($dir in $dirs){
       $path = [io.path]::Combine($destination,$dir)

       if ((Test-Path $path) -eq $false) {
          "Creating $path ..."
          New-Item -Path $path -ItemType Directory | Out-Null
       }else{
          "Exists $path ..."
       }
    }

    $files = GetFilesTree $ftp_uri $user $pass

    foreach($file in $files){
        $source = [io.path]::Combine($ftp_uri,$file)
        $dest = [io.path]::Combine($destination,$file)

        "Downloading $source ..."
        Get-FTPFile $source $dest $user $pass
    }
}

function UploadToFtp($artifacts, $ftp_uri, $user, $pass){
    $webclient = New-Object System.Net.WebClient 
    $webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)  

    foreach($item in Get-ChildItem -recurse $artifacts){ 

        $relpath = [system.io.path]::GetFullPath($item.FullName).SubString([system.io.path]::GetFullPath($artifacts).Length + 1)

        if ($item.Attributes -eq "Directory"){

            try{
                Write-Host Creating $item.Name

                $makeDirectory = [System.Net.WebRequest]::Create($ftp_uri+$relpath);
                $makeDirectory.Credentials = New-Object System.Net.NetworkCredential($user,$pass) 
                $makeDirectory.Method = [System.Net.WebRequestMethods+FTP]::MakeDirectory;
                $makeDirectory.GetResponse();

            }catch [Net.WebException] {
                Write-Host $item.Name probably exists ...
            }

            continue;
        }

        "Uploading $item..."
        $uri = New-Object System.Uri($ftp_uri+$relpath) 
        $webclient.UploadFile($uri, $item.FullName)
    }
}

 function Get-FTPFile ($Source,$Target,$UserName,$Password) 
 { 
     $ftprequest = [System.Net.FtpWebRequest]::create($Source) 
     $ftprequest.Credentials = New-Object System.Net.NetworkCredential($username,$password) 
     $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile 
     $ftprequest.UseBinary = $true 
     $ftprequest.KeepAlive = $false 

     $ftpresponse = $ftprequest.GetResponse() 
     $responsestream = $ftpresponse.GetResponseStream() 

     $targetfile = New-Object IO.FileStream ($Target,[IO.FileMode]::Create) 
     [byte[]]$readbuffer = New-Object byte[] 1024 

     do{ 
         $readlength = $responsestream.Read($readbuffer,0,1024) 
         $targetfile.Write($readbuffer,0,$readlength) 
     } 
     while ($readlength -ne 0) 

     $targetfile.close() 
 } 

#task ListFiles {
#   
#    $files = GetFilesTree 'ftp://127.0.0.1/' "web" "web"
#    $files | ForEach-Object {Write-Host $_ -foregroundcolor cyan}
#}

function GetDirecoryTree($ftp, $user, $pass){
    $creds = New-Object System.Net.NetworkCredential($user,$pass)

    $files = New-Object "system.collections.generic.list[string]"
    $folders = New-Object "system.collections.generic.queue[string]"
    $folders.Enqueue($ftp)

    while($folders.Count -gt 0){
        $fld = $folders.Dequeue()

        $newFiles = GetAllFiles $creds $fld
        $dirs = GetDirectories $creds $fld

        foreach ($line in $dirs){
            $dir = @($newFiles | Where { $line.EndsWith($_) })[0]
            [void]$newFiles.Remove($dir)
            $folders.Enqueue($fld + $dir + "/")

            [void]$files.Add($fld.Replace($ftp, "") + $dir + "/")
        }
    }

    return ,$files
}

function GetFilesTree($ftp, $user, $pass){
    $creds = New-Object System.Net.NetworkCredential($user,$pass)

    $files = New-Object "system.collections.generic.list[string]"
    $folders = New-Object "system.collections.generic.queue[string]"
    $folders.Enqueue($ftp)

    while($folders.Count -gt 0){
        $fld = $folders.Dequeue()

        $newFiles = GetAllFiles $creds $fld
        $dirs = GetDirectories $creds $fld

        foreach ($line in $dirs){
            $dir = @($newFiles | Where { $line.EndsWith($_) })[0]
            [void]$newFiles.Remove($dir)
            $folders.Enqueue($fld + $dir + "/")
        }

        $newFiles | ForEach-Object { 
            $files.Add($fld.Replace($ftp, "") + $_) 
        }
    }

    return ,$files
}

function GetDirectories($creds, $fld){
    $dirs = New-Object "system.collections.generic.list[string]"

    $operation = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
    $reader = GetStream $creds $fld $operation
    while (($line = $reader.ReadLine()) -ne $null) {

       if ($line.Trim().ToLower().StartsWith("d") -or $line.Contains(" <DIR> ")) {
            [void]$dirs.Add($line)
        }
    }
    $reader.Dispose();

    return ,$dirs
}

function GetAllFiles($creds, $fld){
    $newFiles = New-Object "system.collections.generic.list[string]"
    $operation = [System.Net.WebRequestMethods+Ftp]::ListDirectory

    $reader = GetStream $creds $fld $operation

    while (($line = $reader.ReadLine()) -ne $null) {
       [void]$newFiles.Add($line.Trim()) 
    }
    $reader.Dispose();

    return ,$newFiles
}

function GetStream($creds, $url, $meth){

    $ftp = [System.Net.WebRequest]::Create($url)
    $ftp.Credentials = $creds
    $ftp.Method = $meth
    $response = $ftp.GetResponse()

    return New-Object IO.StreamReader $response.GetResponseStream()
}

Export-ModuleMember UploadToFtp, DownLoadFromFtp

how to check if List<T> element contains an item with a Particular Property Value

This is pretty easy to do using LINQ:

var match = pricePublicList.FirstOrDefault(p => p.Size == 200);
if (match == null)
{
    // Element doesn't exist
}

How to replace space with comma using sed?

If you want the output on terminal then,

$sed 's/ /,/g' filename.txt

But if you want to edit the file itself i.e. if you want to replace space with the comma in the file then,

$sed -i 's/ /,/g' filename.txt

Nested JSON: How to add (push) new items to an object?

You can achieve this using Lodash _.assign function.

library[title] = _.assign({}, {'foregrounds': foregrounds }, {'backgrounds': backgrounds });

_x000D_
_x000D_
// This is my JSON object generated from a database_x000D_
var library = {_x000D_
  "Gold Rush": {_x000D_
    "foregrounds": ["Slide 1", "Slide 2", "Slide 3"],_x000D_
    "backgrounds": ["1.jpg", "", "2.jpg"]_x000D_
  },_x000D_
  "California": {_x000D_
    "foregrounds": ["Slide 1", "Slide 2", "Slide 3"],_x000D_
    "backgrounds": ["3.jpg", "4.jpg", "5.jpg"]_x000D_
  }_x000D_
}_x000D_
_x000D_
// These will be dynamically generated vars from editor_x000D_
var title = "Gold Rush";_x000D_
var foregrounds = ["Howdy", "Slide 2"];_x000D_
var backgrounds = ["1.jpg", ""];_x000D_
_x000D_
function save() {_x000D_
_x000D_
  // If title already exists, modify item_x000D_
  if (library[title]) {_x000D_
_x000D_
    // override one Object with the values of another (lodash)_x000D_
    library[title] = _.assign({}, {_x000D_
      'foregrounds': foregrounds_x000D_
    }, {_x000D_
      'backgrounds': backgrounds_x000D_
    });_x000D_
    console.log(library[title]);_x000D_
_x000D_
    // Save to Database. Then on callback..._x000D_
    // console.log('Changes Saved to <b>' + title + '</b>');_x000D_
  }_x000D_
_x000D_
  // If title does not exist, add new item_x000D_
  else {_x000D_
    // Format it for the JSON object_x000D_
    var item = ('"' + title + '" : {"foregrounds" : ' + foregrounds + ',"backgrounds" : ' + backgrounds + '}');_x000D_
_x000D_
    // THE PROBLEM SEEMS TO BE HERE??_x000D_
    // Error: "Result of expression 'library.push' [undefined] is not a function"_x000D_
    library.push(item);_x000D_
_x000D_
    // Save to Database. Then on callback..._x000D_
    console.log('Added: <b>' + title + '</b>');_x000D_
  }_x000D_
}_x000D_
_x000D_
save();
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Problem in running .net framework 4.0 website on iis 7.0

Depending on the type of application, another thing to check is under the Advanced Settings for the Application Pool make sure "Enable 32-Bit Applications" is set to True.

I'd checked everything in this thread when I had this issue but all had already been setup correctly, I found this was the problem for me.

Create a SQL query to retrieve most recent records

Add an auto incrementing Primary Key to each record, for example, UserStatusId.

Then your query could look like this:

select * from UserStatus where UserStatusId in
(
    select max(UserStatusId) from UserStatus group by User
)

Date User Status Notes

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

I faced the similar issue on importing maven with testng project. This was solved by converting again into TestNg project by

right click on eclipse project > TestNG > Convert to TestNG

and replacing the existing testng.xml file with the newly created. Clean and update the maven project with mvn install

Note: take backup of your testng.xml

Android ADB doesn't see device

The normal way to fix this is indeed to restart the adb server :

adb kill-server
adb start-server

then

adb devices -l 

should list connected devices

But it possible that it doesnt fix the problem. It appends to me.

I had to disable/enable the debug mode on the device, and then restart adb server.

Differences between arm64 and aarch64

It seems that ARM64 was created by Apple and AARCH64 by the others, most notably GNU/GCC guys.

After some googling I found this link:

The LLVM 64-bit ARM64/AArch64 Back-Ends Have Merged

So it makes sense, iPad calls itself ARM64, as Apple is using LLVM, and Edge uses AARCH64, as Android is using GNU GCC toolchain.

How to get cumulative sum

select t1.id, t1.SomeNumt, SUM(t2.SomeNumt) as sum
from @t t1
inner join @t t2 on t1.id >= t2.id
group by t1.id, t1.SomeNumt
order by t1.id

SQL Fiddle example

Output

| ID | SOMENUMT | SUM |
-----------------------
|  1 |       10 |  10 |
|  2 |       12 |  22 |
|  3 |        3 |  25 |
|  4 |       15 |  40 |
|  5 |       23 |  63 |

Edit: this is a generalized solution that will work across most db platforms. When there is a better solution available for your specific platform (e.g., gareth's), use it!

Is there a way to @Autowire a bean that requires constructor arguments?

Another alternative, if you already have an instance of the object created and you want to add it as an @autowired dependency to initialize all the internal @autowired variables, could be the following:

@Autowired 
private AutowireCapableBeanFactory autowireCapableBeanFactory;

public void doStuff() {
   YourObject obj = new YourObject("Value X", "etc");
   autowireCapableBeanFactory.autowireBean(obj);
}

How to post a file from a form with Axios

Sample application using Vue. Requires a backend server running on localhost to process the request:

var app = new Vue({
  el: "#app",
  data: {
    file: ''
  },
  methods: {
    submitFile() {
      let formData = new FormData();
      formData.append('file', this.file);
      console.log('>> formData >> ', formData);

      // You should have a server side REST API 
      axios.post('http://localhost:8080/restapi/fileupload',
          formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }
        ).then(function () {
          console.log('SUCCESS!!');
        })
        .catch(function () {
          console.log('FAILURE!!');
        });
    },
    handleFileUpload() {
      this.file = this.$refs.file.files[0];
      console.log('>>>> 1st element in files array >>>> ', this.file);
    }
  }
});

https://codepen.io/pmarimuthu/pen/MqqaOE

How to print something to the console in Xcode?

3 ways to do this:

In C Language (Command Line Tool) Works with Objective C, too:

printf("Hello World");

In Objective C:

NSLog(@"Hello, World!");

In Objective C with variables:

NSString * myString = @"Hello World";
NSLog(@"%@", myString);

In the code with variables, the variable created with class, NSString was outputted be NSLog. The %@ represents text as a variable.

Moment JS - check if a date is today or in the future

You can use the isAfter() query function of momentjs:

Check if a moment is after another moment.

moment('2010-10-20').isAfter('2010-10-19'); // true

If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.

moment('2010-10-20').isAfter('2010-01-01', 'year'); // false

moment('2010-10-20').isAfter('2009-12-31', 'year'); // true

http://momentjs.com/docs/#/query/is-after/

Simple JavaScript problem: onClick confirm not preventing default action

I've had issue with IE7 and returning false before.

Check my answer here to another problem: Javascript not running on IE

python exception message capturing

You have to define which type of exception you want to catch. So write except Exception, e: instead of except, e: for a general exception (that will be logged anyway).

Other possibility is to write your whole try/except code this way:

try:
    with open(filepath,'rb') as f:
        con.storbinary('STOR '+ filepath, f)
    logger.info('File successfully uploaded to '+ FTPADDR)
except Exception, e: # work on python 2.x
    logger.error('Failed to upload to ftp: '+ str(e))

in Python 3.x and modern versions of Python 2.x use except Exception as e instead of except Exception, e:

try:
    with open(filepath,'rb') as f:
        con.storbinary('STOR '+ filepath, f)
    logger.info('File successfully uploaded to '+ FTPADDR)
except Exception as e: # work on python 3.x
    logger.error('Failed to upload to ftp: '+ str(e))

CSS "color" vs. "font-color"

The same way Boston came up with its street plan. They followed the cow paths already there, and built houses where the streets weren't, and after a while it was too much trouble to change.

installation app blocked by play protect

Try to create a new key store and replace with old one, then rebuild a new signed APK.

Update: Note that if you're using a http connection with server ,you should use SSL.

Take a look at: https://developer.android.com/distribute/best-practices/develop/understand-play-policies

How to set default value for HTML select?

You first need to add values to your select options and for easy targetting give the select itself an id.

Let's make option b the default:

<select id="mySelect">
    <option>a</option>
    <option selected="selected">b</option>
    <option>c</option>
</select>

Now you can change the default selected value with JavaScript like this:

<script>
var temp = "a";
var mySelect = document.getElementById('mySelect');

for(var i, j = 0; i = mySelect.options[j]; j++) {
    if(i.value == temp) {
        mySelect.selectedIndex = j;
        break;
    }
}
</script>

See it in action on codepen.

How to add extension methods to Enums

A Simple workaround.

public static class EnumExtensions
{
    public static int ToInt(this Enum payLoad) {

        return ( int ) ( IConvertible ) payLoad;

    }
}

int num = YourEnum.AItem.ToInt();
Console.WriteLine("num : ", num);

How do I read the source code of shell commands?

ls is part of coreutils. You can get it with git :

git clone git://git.sv.gnu.org/coreutils

You'll find coreutils listed with other packages (scroll to bottom) on this page.

JavaFX: How to get stage from controller during initialization?

All you need is to give the AnchorPane an ID, and then you can get the Stage from that.

@FXML private AnchorPane ap;
Stage stage = (Stage) ap.getScene().getWindow();

From here, you can add in the Listener that you need.

Edit: As stated by EarthMind below, it doesn't have to be the AnchorPane element; it can be any element that you've defined.

How to get rid of blank pages in PDF exported from SSRS

I have worked with SSRS for over 10 years and the answers above are the go to answers. BUT. If nothing works, and you are completely stuffed....remove items from the report until the problem goes away. Once you have identified which row or report item is causing the problem, put it inside a rectangle container. That's it. Has helped us many many times! Extra pages are mostly caused by report items flowing over the right margin. When all else fails, putting things inside a rectangle or an empty rectangle to the right of an item, can stop this from happening. Good luck out there!

Are the shift operators (<<, >>) arithmetic or logical in C?

GCC does

  1. for -ve - > Arithmetic Shift

  2. For +ve -> Logical Shift

CGContextDrawImage draws image upside down when passed UIImage.CGImage

drawInRect is certainly the way to go. Here's another little thing that will come in way useful when doing this. Usually the picture and the rectangle into which it is going to go don't conform. In that case drawInRect will stretch the picture. Here's a quick and cool way to make sure that the picture's aspect ration isn't changed, by reversing the transformation (which will be to fit the whole thing in):

//Picture and irect don't conform, so there'll be stretching, compensate
    float xf = Picture.size.width/irect.size.width;
    float yf = Picture.size.height/irect.size.height;
    float m = MIN(xf, yf);
    xf /= m;
    yf /= m;
    CGContextScaleCTM(ctx, xf, yf);

    [Picture drawInRect: irect];

PuTTY Connection Manager download?

PuTTY Session Manager is a tool that allows system administrators to organise their PuTTY sessions into folders and assign hotkeys to favourite sessions. Multiple sessions can be launched with one click. Requires MS Windows and the .NET 2.0 Runtime.

http://sourceforge.net/projects/puttysm/

Selenium Webdriver: Entering text into text field

Agree with Subir Kumar Sao and Faiz.

element_enter.findElement(By.xpath("//html/body/div[1]/div[3]/div[1]/form/div/div/input")).sendKeys(barcode);

How to make a div center align in HTML

it depends if your div is in position: absolute / fixed or relative / static

for position: absolute & fixed

<div style="position: absolute; /*or fixed*/;
width: 50%;
height: 300px;
left: 50%;
top:100px;
margin: 0 0 0 -25%">blblablbalba</div>

The trick here is to have a negative margin half the width of the object

for position: relative & static

<div style="position: relative; /*or static*/;
width: 50%;
height: 300px;
margin: 0 auto">blblablbalba</div>

for both techniques, it is imperative to set the width.

How to Right-align flex item?

As easy as

.main {
    display: flex;
    flex-direction:row-reverse;
}

Pair/tuple data type in Go

You could do something like this if you wanted

package main

import "fmt"

type Pair struct {
    a, b interface{}
}

func main() {
    p1 := Pair{"finished", 42}
    p2 := Pair{6.1, "hello"}
    fmt.Println("p1=", p1, "p2=", p2)
    fmt.Println("p1.b", p1.b)
    // But to use the values you'll need a type assertion
    s := p1.a.(string) + " now"
    fmt.Println("p1.a", s)
}

However I think what you have already is perfectly idiomatic and the struct describes your data perfectly which is a big advantage over using plain tuples.

php - push array into array - key issue

Use this..

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
    $res_arr_values[] = $row;
}

Activity restart on rotation Android

Even though it is not "the Android way" I have gotten very good results by handling orientation changes myself and simply repositioning the widgets within a view to take the altered orientation into account. This is faster than any other approach, because your views do not have to be saved and restored. It also provides a more seamless experience to the user, because the respositioned widgets are exactly the same widgets, just moved and/or resized. Not only model state, but also view state, can be preserved in this manner.

RelativeLayout can sometimes be a good choice for a view that has to reorient itself from time to time. You just provide a set of portrait layout params and a set of landscaped layout params, with different relative positioning rules on each, for each child widget. Then, in your onConfigurationChanged() method, you pass the appropriate one to a setLayoutParams() call on each child. If any child control itself needs to be internally reoriented, you just call a method on that child to perform the reorientation. That child similarly calls methods on any of its child controls that need internal reorientation, and so on.

How to include file in a bash shell script

Syntax is source <file-name>

ex. source config.sh

script - config.sh

USERNAME="satish"
EMAIL="[email protected]"

calling script -

#!/bin/bash
source config.sh
echo Welcome ${USERNAME}!
echo Your email is ${EMAIL}.

You can learn to include a bash script in another bash script here.

What's the purpose of the LEA instruction?

Another important feature of the LEA instruction is that it does not alter the condition codes such as CF and ZF, while computing the address by arithmetic instructions like ADD or MUL does. This feature decreases the level of dependency among instructions and thus makes room for further optimization by the compiler or hardware scheduler.

How to overload __init__ method based on argument type?

OK, great. I just tossed together this example with a tuple, not a filename, but that's easy. Thanks all.

class MyData:
    def __init__(self, data):
        self.myList = []
        if isinstance(data, tuple):
            for i in data:
                self.myList.append(i)
        else:
            self.myList = data

    def GetData(self):
        print self.myList

a = [1,2]

b = (2,3)

c = MyData(a)

d = MyData(b)

c.GetData()

d.GetData()

[1, 2]

[2, 3]

Alternate table with new not null Column in existing table in SQL

Choose either:

a) Create not null with some valid default value
b) Create null, fill it, alter to not null

Scheduling Python Script to run every hour accurately

Run the script every 15 minutes of the hour. For example, you want to receive 15 minute stock price quotes, which are updated every 15 minutes.

while True:
    print("Update data:", datetime.now())
    sleep = 15 - datetime.now().minute % 15
    if sleep == 15:
        run_strategy()
        time.sleep(sleep * 60)
    else:
        time.sleep(sleep * 60)

How to hide 'Back' button on navigation bar on iPhone?

For me none of the above seemed to work, It had no visual effect. I am using storyboards with a view that is "embedded" in a navigation controller.

I then at code level add my menuItems and for some reason the "backButton" is visible when visually debugging the view hierarchy, and my menuItem Icon is displayed beneath the invisible "back button".

I tried the settings, as suggested at the various hook methods and that had no effect. Then I tried a more brutal approach and iterate over the subview which also had no effect.

I inspected my icon sizes and appeared to be ok. After referring to he apple Human Interface Guideline I confirmed my Icons are correct. (1 pixel smaller in my case 24px 48px 72px).

The strangest part then is the actual fix...

When adding the BarButton Item give it a title with at least one character, In my case a space character.

Hopes this helps someone.

//left menu - the title must have a space
UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc] initWithTitle:@" " <--THE FIX 
                                                                    style:UIBarButtonItemStylePlain
                                                                  target:self
                                                                  action:@selector(showMenu)];
leftButtonItem.image = [UIImage imageNamed:@"ic_menu"];

[self.navigationItem setLeftBarButtonItem:leftButtonItem];

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

Getting min and max Dates from a pandas dataframe

min(df['some_property'])
max(df['some_property'])

The built-in functions work well with Pandas Dataframes.

Check if number is decimal

You can get most of what you want from is_float, but if you really need to know whether it has a decimal in it, your function above isn't terribly far (albeit the wrong language):

function is_decimal( $val )
{
    return is_numeric( $val ) && floor( $val ) != $val;
}

Reading *.wav files in Python

u can also use simple import wavio library u also need have some basic knowledge of the sound.

Angular 2 How to redirect to 404 or other path if the path does not exist

As Angular moved on with the release, I faced this same issue. As per version 2.1.0 the Route interface looks like:

export interface Route {
    path?: string;
    pathMatch?: string;
    component?: Type<any>;
    redirectTo?: string;
    outlet?: string;
    canActivate?: any[];
    canActivateChild?: any[];
    canDeactivate?: any[];
    canLoad?: any[];
    data?: Data;
    resolve?: ResolveData;
    children?: Route[];
    loadChildren?: LoadChildren;
} 

So my solutions was the following:

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: '404', component: NotFoundComponent },
    { path: '**', redirectTo: '404' }
];

Save PHP variables to a text file

This should do what you want, but without more context I can't tell for sure.

Writing $text to a file:

$text = "Anything";
$var_str = var_export($text, true);
$var = "<?php\n\n\$text = $var_str;\n\n?>";
file_put_contents('filename.php', $var);

Retrieving it again:

include 'filename.php';
echo $text;

How to reference a method in javadoc?

you can use @see to do that:

sample:

interface View {
        /**
         * @return true: have read contact and call log permissions, else otherwise
         * @see #requestReadContactAndCallLogPermissions()
         */
        boolean haveReadContactAndCallLogPermissions();

        /**
         * if not have permissions, request to user for allow
         * @see #haveReadContactAndCallLogPermissions()
         */
        void requestReadContactAndCallLogPermissions();
    }

Difference between logger.info and logger.debug

Just a clarification about the set of all possible levels, that are:

ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF

System.IO.IOException: file used by another process

My reputation being too small to comment an answer, here is my feedback concerning roquen answer (using settings on xmlwriter to force the stream to close): it works perfectly and it made me save a lot of time. roquen's example requires some adjustment, here is the code that works on .NET framework 4.8 :

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.CloseOutput = true;
    writer = XmlWriter.Create(stream, settings);

pod has unbound PersistentVolumeClaims

You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.

When using storageClass Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.


To solve your issue:

  • Provide a PersistentVolume fulfilling the constraints of the claim (a size >= 100Mi)
  • Remove the storageClass-line from the PersistentVolumeClaim
  • Remove the StorageClass from your cluster

How do these pieces play together?

At creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.

The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.

The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.

A PersistentVolume without StorageClass is considered to be static.

"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.


Example PersistentVolume

In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: ckan-pv-home
  labels:
    type: local
spec:
  capacity:
    storage: 100Mi
  hostPath:
    path: "/mnt/data/ckan"

The PersistentVolumeSpec allows us to define multiple attributes. I chose a hostPath volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.


Additional Resources:

What is Ad Hoc Query?

An Ad-Hoc Query is a query that cannot be determined prior to the moment the query is issued. It is created in order to get information when need arises and it consists of dynamically constructed SQL which is usually constructed by desktop-resident query tools.

Check: http://www.learn.geekinterview.com/data-warehouse/dw-basics/what-is-an-ad-hoc-query.html

fix java.net.SocketTimeoutException: Read timed out

Here are few pointers/suggestions for investigation

  1. I see that every time you vote, you call vote method which creates a fresh HTTP connection.
  2. This might be a problem. I would suggest to use a single HttpClient instance to post to the server. This way it wont create too many connections from the client side.
  3. At the end of everything, HttpClient needs to be shut and hence call httpclient.getConnectionManager().shutdown(); to release the resources used by the connections.

Plot size and resolution with R markdown, knitr, pandoc, beamer

Figure sizes are specified in inches and can be included as a global option of the document output format. For example:

---
title: "My Document"
output:
  html_document:
    fig_width: 6
    fig_height: 4
---

And the plot's size in the graphic device can be increased at the chunk level:

```{r, fig.width=14, fig.height=12}          #Expand the plot width to 14 inches

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

You can also use the out.width and out.height arguments to directly define the size of the plot in the output file:

```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

How do I run SSH commands on remote system using Java?

I created solution based on JSch library:

import com.google.common.io.CharStreams
import com.jcraft.jsch.ChannelExec
import com.jcraft.jsch.JSch
import com.jcraft.jsch.JSchException
import com.jcraft.jsch.Session

import static java.util.Arrays.asList

class RunCommandViaSsh {

    private static final String SSH_HOST = "test.domain.com"
    private static final String SSH_LOGIN = "username"
    private static final String SSH_PASSWORD = "password"

    public static void main() {
        System.out.println(runCommand("pwd"))
        System.out.println(runCommand("ls -la"));
    }

    private static List<String> runCommand(String command) {
        Session session = setupSshSession();
        session.connect();

        ChannelExec channel = (ChannelExec) session.openChannel("exec");
        try {
            channel.setCommand(command);
            channel.setInputStream(null);
            InputStream output = channel.getInputStream();
            channel.connect();

            String result = CharStreams.toString(new InputStreamReader(output));
            return asList(result.split("\n"));

        } catch (JSchException | IOException e) {
            closeConnection(channel, session)
            throw new RuntimeException(e)

        } finally {
            closeConnection(channel, session)
        }
    }

    private static Session setupSshSession() {
        Session session = new JSch().getSession(SSH_LOGIN, SSH_HOST, 22);
        session.setPassword(SSH_PASSWORD);
        session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
        session.setConfig("StrictHostKeyChecking", "no"); // disable check for RSA key
        return session;
    }

    private static void closeConnection(ChannelExec channel, Session session) {
        try {
            channel.disconnect()
        } catch (Exception ignored) {
        }
        session.disconnect()
    }
}

How do you comment an MS-access Query?

I decided to add a condition to the Where Clause that always evaluates true but allows the coder to find your comment.

Select
   ...
From
   ...
Where
   ....
   And "Comment: FYI, Access doesn't support normal comments!"<>""

The last line always evaluates to true so it doesn't affect the data returned but allows you to leave a comment for the next guy.

Error #2032: Stream Error

Just to clarify my comment (it's illegible in a single line)

I think the best answer is the comment by Mike Chambers in this link (http://www.judahfrangipane.com/blog/2007/02/15/error-2032-stream-error/) by Hunter McMillen.

A note from Mike Chambers:

If you run into this using URLLoader, listen for the:

flash.events.HTTPStatusEvent.HTTP_STATUS

and in AIR :

flash.events.HTTPStatusEvent.HTTP_RESPONSE_STATUS

It should give you some more information (such as the status code being returned from the server).

How to copy directory recursively in python and overwrite all?

Have a look at the shutil package, especially rmtree and copytree. You can check if a file / path exists with os.paths.exists(<path>).

import shutil
import os

def copy_and_overwrite(from_path, to_path):
    if os.path.exists(to_path):
        shutil.rmtree(to_path)
    shutil.copytree(from_path, to_path)

Vincent was right about copytree not working, if dirs already exist. So distutils is the nicer version. Below is a fixed version of shutil.copytree. It's basically copied 1-1, except the first os.makedirs() put behind an if-else-construct:

import os
from shutil import *
def copytree(src, dst, symlinks=False, ignore=None):
    names = os.listdir(src)
    if ignore is not None:
        ignored_names = ignore(src, names)
    else:
        ignored_names = set()

    if not os.path.isdir(dst): # This one line does the trick
        os.makedirs(dst)
    errors = []
    for name in names:
        if name in ignored_names:
            continue
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        try:
            if symlinks and os.path.islink(srcname):
                linkto = os.readlink(srcname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                copytree(srcname, dstname, symlinks, ignore)
            else:
                # Will raise a SpecialFileError for unsupported file types
                copy2(srcname, dstname)
        # catch the Error from the recursive copytree so that we can
        # continue with other files
        except Error, err:
            errors.extend(err.args[0])
        except EnvironmentError, why:
            errors.append((srcname, dstname, str(why)))
    try:
        copystat(src, dst)
    except OSError, why:
        if WindowsError is not None and isinstance(why, WindowsError):
            # Copying file access times may fail on Windows
            pass
        else:
            errors.extend((src, dst, str(why)))
    if errors:
        raise Error, errors

Is it possible to use jQuery to read meta tags

jQuery now supports .data();, so if you have

<div id='author' data-content='stuff!'>

use

var author = $('#author').data("content"); // author = 'stuff!'

cmake and libpthread

The following should be clean (using find_package) and work (the find module is called FindThreads):

cmake_minimum_required (VERSION 2.6) 
find_package (Threads)
add_executable (myapp main.cpp ...)
target_link_libraries (myapp ${CMAKE_THREAD_LIBS_INIT})

How do I read / convert an InputStream into a String in Java?

Taking into account file one should first get a java.io.Reader instance. This can then be read and added to a StringBuilder (we don't need StringBuffer if we are not accessing it in multiple threads, and StringBuilder is faster). The trick here is that we work in blocks, and as such don't need other buffering streams. The block size is parameterized for run-time performance optimization.

public static String slurp(final InputStream is, final int bufferSize) {
    final char[] buffer = new char[bufferSize];
    final StringBuilder out = new StringBuilder();
    try (Reader in = new InputStreamReader(is, "UTF-8")) {
        for (;;) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
    }
    catch (UnsupportedEncodingException ex) {
        /* ... */
    }
    catch (IOException ex) {
        /* ... */
    }
    return out.toString();
}

Array initialization in Perl

To produce the output in your comment to your post, this will do it:

use strict;
use warnings;

my @other_array = (0,0,0,1,2,2,3,3,3,4);
my @array;
my %uniqs;

$uniqs{$_}++ for @other_array;

foreach (keys %uniqs) { $array[$_]=$uniqs{$_} }

print "array[$_] = $array[$_]\n" for (0..$#array);

Output:

   array[0] = 3
   array[1] = 1
   array[2] = 2
   array[3] = 3
   array[4] = 1

This is different than your stated algorithm of producing a parallel array with zero values, but it is a more Perly way of doing it...

If you must have a parallel array that is the same size as your first array with the elements initialized to 0, this statement will dynamically do it: @array=(0) x scalar(@other_array); but really, you don't need to do that.

Android Split string

android split string by comma

String data = "1,Diego Maradona,Footballer,Argentina";
String[] items = data.split(",");
for (String item : items)
{
    System.out.println("item = " + item);
}

How to show validation message below each textbox using jquery?

is only the matter of finding the dom where you want to insert the the text.

DEMO jsfiddle

$().text(); 

Get value of a specific object property in C# without knowing the class behind

You can do it using dynamic instead of object:

dynamic item = AnyFunction(....);
string value = item.name;

Note that the Dynamic Language Runtime (DLR) has built-in caching mechanisms, so subsequent calls are very fast.

Excel VBA Loop on columns

Yes, let's use Select as an example

sample code: Columns("A").select

How to loop through Columns:

Method 1: (You can use index to replace the Excel Address)

For i = 1 to 100
    Columns(i).Select
next i

Method 2: (Using the address)

For i = 1 To 100
 Columns(Columns(i).Address).Select
Next i

EDIT: Strip the Column for OP

columnString = Replace(Split(Columns(27).Address, ":")(0), "$", "")

e.g. you want to get the 27th Column --> AA, you can get it this way

Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?

While I can see that 1=1 would be useful for generated SQL, a technique I use in PHP is to create an array of clauses and then do

implode (" AND ", $clauses);

thus avoiding the problem of having a leading or trailing AND. Obviously this is only useful if you know that you are going to have at least one clause!

BACKUP LOG cannot be performed because there is no current database backup

I fixed my error on restoring to non-existing DB from SQL 2008 to SQL 2014 by putting a check mark on Relocating to the new SQL2014 folder location.