Programs & Examples On #Linktable

Uncaught ReferenceError: jQuery is not defined

you need to put it after wp_head(); Because that loads your jQuery and you need to load jQuery first and then your js

How do you turn a Mongoose document into a plain object?

the fast way if the property is not in the model :

document.set( key,value, { strict: false });

Git status shows files as changed even though contents are the same

After copying my local repository and working copy to another folder (on Windows by the way), I had four files that kept showing up as changed and tried every suggestion listed in the other answers. In the end what fixed it for me was deleting the local branch and downloading it again from the remote. In my case I guess it had something to do with copying a local repository rather than cloning.

IntelliJ and Tomcat.. Howto..?

You can also debug tomcat using the community edition (Unlike what is said above).

Start tomcat in debug mode, for example like this: .\catalina.bat jpda run

In intellij: Run > Edit Configurations > +

Select "Remote" Name the connection: "somename" Set "Port:" 8000 (default 5005)

Select Run > Debug "somename"

Regex expressions in Java, \\s vs. \\s+

The first one matches a single whitespace, whereas the second one matches one or many whitespaces. They're the so-called regular expression quantifiers, and they perform matches like this (taken from the documentation):

Greedy quantifiers
X?  X, once or not at all
X*  X, zero or more times
X+  X, one or more times
X{n}    X, exactly n times
X{n,}   X, at least n times
X{n,m}  X, at least n but not more than m times

Reluctant quantifiers
X?? X, once or not at all
X*? X, zero or more times
X+? X, one or more times
X{n}?   X, exactly n times
X{n,}?  X, at least n times
X{n,m}? X, at least n but not more than m times

Possessive quantifiers
X?+ X, once or not at all
X*+ X, zero or more times
X++ X, one or more times
X{n}+   X, exactly n times
X{n,}+  X, at least n times
X{n,m}+ X, at least n but not more than m times

How to calculate rolling / moving average using NumPy / SciPy?

I actually wanted a slightly different behavior than the accepted answer. I was building a moving average feature extractor for an sklearn pipeline, so I required that the output of the moving average have the same dimension as the input. What I want is for the moving average to assume the series stays constant, ie a moving average of [1,2,3,4,5] with window 2 would give [1.5,2.5,3.5,4.5,5.0].

For column vectors (my use case) we get

def moving_average_col(X, n):
  z2 = np.cumsum(np.pad(X, ((n,0),(0,0)), 'constant', constant_values=0), axis=0)
  z1 = np.cumsum(np.pad(X, ((0,n),(0,0)), 'constant', constant_values=X[-1]), axis=0)
  return (z1-z2)[(n-1):-1]/n

And for arrays

def moving_average_array(X, n):
  z2 = np.cumsum(np.pad(X, (n,0), 'constant', constant_values=0))
  z1 = np.cumsum(np.pad(X, (0,n), 'constant', constant_values=X[-1]))
  return (z1-z2)[(n-1):-1]/n

Of course, one doesn't have to assume constant values for the padding, but doing so should be adequate in most cases.

Set background image according to screen resolution

I've had this same issue but have now found the resolution for it.

The trick is to create a wallpaper image of 1920*1200. When you then apply this wallpaper to the different machines, Windows 7 automatically resizes for best fit.

Hope this helps you all

Codeigniter $this->input->post() empty while $_POST is working correctly

My issue was with an ajax call. I was using this:

type: 'posts',

instead of

type: 'post',

Syntax, D'oh!

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

For completeness sake, also a solution with Joda-Time version 2.5 and its DateTime class:

new Timestamp(new DateTime(2007, 9, 23, 0, 0, DateTimeZone.forID( "America/Montreal" )).getMillis())

Simple pagination in javascript

enter image description here file:icons.svg

<svg aria-hidden="true" style="position: absolute; width: 0; height: 0; overflow: hidden;" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<symbol id="icon-triangle-left" viewBox="0 0 20 20">
<title>triangle-left</title>
<path d="M14 5v10l-9-5 9-5z"></path>
</symbol>
<symbol id="icon-triangle-right" viewBox="0 0 20 20">
<title>triangle-right</title>
<path d="M15 10l-9 5v-10l9 5z"></path>
</symbol>
</defs>
</svg>

file: style.css

 .results__btn--prev{
    float: left;
    flex-direction: row-reverse; }
  .results__btn--next{
    float: right; }

file index.html:

<body>
<form class="search">
                <input type="text" class="search__field" placeholder="Search over 1,000,000 recipes...">
                <button class="btn search__btn">
                    <svg class="search__icon">
                        <use href="img/icons.svg#icon-magnifying-glass"></use>
                    </svg>
                    <span>Search</span>
                </button>
            </form>
     <div class="results">
         <ul class="results__list">
         </ul>
         <div class="results__pages">
         </div>
     </div>
</body>

file: searchView.js

export const element = {
    searchForm:document.querySelector('.search'),
    searchInput: document.querySelector('.search__field'),
    searchResultList: document.querySelector('.results__list'),
    searchRes:document.querySelector('.results'),
    searchResPages:document.querySelector('.results__pages')

}
export const getInput = () => element.searchInput.value;
export const clearResults = () =>{
    element.searchResultList.innerHTML=``;
    element.searchResPages.innerHTML=``;
}
export const clearInput = ()=> element.searchInput.value = "";

const limitRecipeTitle = (title, limit=17)=>{
    const newTitle = [];
    if(title.length>limit){
        title.split(' ').reduce((acc, cur)=>{
            if(acc+cur.length <= limit){
                newTitle.push(cur);
            }
            return acc+cur.length;
        },0);
    }

    return `${newTitle.join(' ')} ...`
}
const renderRecipe = recipe =>{
    const markup = `
        <li>
            <a class="results__link" href="#${recipe.recipe_id}">
                <figure class="results__fig">
                    <img src="${recipe.image_url}" alt="${limitRecipeTitle(recipe.title)}">
                </figure>
                <div class="results__data">
                    <h4 class="results__name">${recipe.title}</h4>
                    <p class="results__author">${recipe.publisher}</p>
                </div>
            </a>
        </li>
    `;
    var htmlObject = document.createElement('div');
    htmlObject.innerHTML = markup;
    element.searchResultList.insertAdjacentElement('beforeend',htmlObject);
}

const createButton = (page, type)=>`

    <button class="btn-inline results__btn--${type}" data-goto=${type === 'prev'? page-1 : page+1}>
    <svg class="search__icon">
        <use href="img/icons.svg#icon-triangle-${type === 'prev'? 'left' : 'right'}}"></use>
    </svg>
    <span>Page ${type === 'prev'? page-1 : page+1}</span>
    </button>
`
const renderButtons = (page, numResults, resultPerPage)=>{
    const pages = Math.ceil(numResults/resultPerPage);
    let button;
    if(page == 1 && pages >1){
        //button to go to next page
        button = createButton(page, 'next');
    }else if(page<pages){
      //both buttons  
      button = `
      ${createButton(page, 'prev')}
      ${createButton(page, 'next')}`;


    }
    else if (page === pages && pages > 1){
        //Only button to go to prev page
        button = createButton(page, 'prev');
    }

    element.searchResPages.insertAdjacentHTML('afterbegin', button);
}
export const renderResults = (recipes, page=1, resultPerPage=10) =>{
    /*//recipes.foreach(el=>renderRecipe(el))
    //or foreach will automatically call the render recipes
    //recipes.forEach(renderRecipe)*/
    const start = (page-1)*resultPerPage;
    const end = page * resultPerPage;
    recipes.slice(start, end).forEach(renderRecipe);
    renderButtons(page, recipes.length, resultPerPage);
}

file: Search.js

export default class Search{
    constructor(query){
        this.query = query;
    }
    async getResults(){
        try{
            const res = await axios(`https://api.com/api/search?&q=${this.query}`);
            this.result = res.data.recipes;
            //console.log(this.result);
        }catch(error){
            alert(error);
        }
    }
}

file: Index.js

onst state = {};
const controlSearch = async()=>{
  const query = searchView.getInput();
  if (query){
    state.search = new Search(query); 
    searchView.clearResults();
    searchView.clearInput();
    await state.search.getResults();
    searchView.renderResults(state.search.result);
  }
}
//event listner to the parent object to delegate the event
element.searchForm.addEventListener('submit', event=>{
  console.log("submit search");
  event.preventDefault();
  controlSearch();
});

element.searchResPages.addEventListener('click', e=>{
  const btn = e.target.closest('.btn-inline');
  if(btn){
    const goToPage = parseInt(btn.dataset.goto, 10);//base 10
    searchView.clearResults();
    searchView.renderResults(state.search.result, goToPage);
  }
});

A CSS selector to get last visible div

Pure JS solution (eg. when you don't use jQuery or another framework to other things and don't want to download that just for this task):

<div>A</div>
<div>B</div>  
<div>C</div>  
<div style="display:none">D</div>
<div style="display:none">E</div>    

<script>
var divs = document.getElementsByTagName('div');
var last;

if (divs) {
    for (var i = 0; i < divs.length; i++) {
        if (divs[i].style.display != 'none') {
            last = divs[i];           
        }
    }
}

if (last) {
    last.style.background = 'red';
}
</script>

http://jsfiddle.net/uEeaA/90/

MVC Razor @foreach

What is the best practice on where the logic for the @foreach should be at?

Nowhere, just get rid of it. You could use editor or display templates.

So for example:

@foreach (var item in Model.Foos)
{
    <div>@item.Bar</div>
}

could perfectly fine be replaced by a display template:

@Html.DisplayFor(x => x.Foos)

and then you will define the corresponding display template (if you don't like the default one). So you would define a reusable template ~/Views/Shared/DisplayTemplates/Foo.cshtml which will automatically be rendered by the framework for each element of the Foos collection (IEnumerable<Foo> Foos { get; set; }):

@model Foo
<div>@Model.Bar</div>

Obviously exactly the same conventions apply for editor templates which should be used in case you want to show some input fields allowing you to edit the view model in contrast to just displaying it as readonly.

Count all duplicates of each value

SELECT number, COUNT(*)
    FROM YourTable
    GROUP BY number
    ORDER BY number

How to resolve the "ADB server didn't ACK" error?

I've got a kind of botch for the old ADB server didn't ACK * failed to start daemon * issue which might help, though i haven't seen anyone else with my problem so maybe not. Anyway...

I changed the default install location for my HTC sensation to 2 (SD card), but when trying to revert back to 0 (internal) i was getting this error. Looking in task manager showed there were 2 instances of adb.exe running, one of which kept stopping and starting and was impossible to kill, the other could be killed but then a new instance would start almost immediately.

The only way i could get adb to start successfully was to get my command ready in the command window, go to task manager to end the adb.exe, then when the window came up saying 'are you sure you want to kill adb.exe' dragged that over the command window, clicked OK then immediately pressed Enter to run the command. It seems that the short window between adb.exe being killed and restarting itself is sufficient to run a command, though if you try to do something else it won't work and you have to repeat this process each time you want to run a command.

PITA but it's the only way an uneducated numpty like myself could get round it - hopefully it'll help someone...

iOS: Convert UTC NSDate to local Timezone

Swift 3+: UTC to Local and Local to UTC

extension Date {

    // Convert UTC (or GMT) to local time
    func toLocalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }

    // Convert local time to UTC (or GMT)
    func toGlobalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }
}

Plotting power spectrum in python

Since FFT is symmetric over it's centre, half the values are just enough.

import numpy as np
import matplotlib.pyplot as plt

fs = 30.0
t = np.arange(0,10,1/fs)
x = np.cos(2*np.pi*10*t)

xF = np.fft.fft(x)
N = len(xF)
xF = xF[0:N/2]
fr = np.linspace(0,fs/2,N/2)

plt.ion()
plt.plot(fr,abs(xF)**2)

Return an empty Observable

Or you can try ignoreElements() as well

scale Image in an UIButton to AspectFit?

I had problems with the image not resizing proportionately so the way I fixed it was using edge insets.

fooButton.contentEdgeInsets = UIEdgeInsetsMake(10, 15, 10, 15);

Remove spacing between table cells and rows

I had a similar problem and I solved it by (inline)styling the td element as follows :

<td style="display: block;"> 

This will work although its not the best practice. In my case I was working on a old template that had been styled using HTML tables.

Python can't find module in the same folder

If you are sure that all the modules, files you're trying to import are in the same folder and they should be picked directly just by giving the name and not the reference path then your editor or terminal should have opened the main folder where all the files/modules are present.

Either, try running from Terminal, make sure first you go to the correct directory.

cd path to the root folder where all the modules are

python script.py

Or if running [F5] from the editor i.e VsCode then open the complete folder there and not the individual files.

What is the best Java email address validation method?

You may also want to check for the length - emails are a maximum of 254 chars long. I use the apache commons validator and it doesn't check for this.

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

<% %>

Executes the ruby code within the brackets.

<%= %>

Prints something into erb file.

<%== %>

Equivalent to <%= raw %>. Prints something verbatim (i.e. w/o escaping) into erb file. (Taken from Ruby on Rails Guides.)

<% -%>

Avoids line break after expression.

<%# %>

Comments out code within brackets; not sent to client (as opposed to HTML comments).

Visit Ruby Doc for more infos about ERB.

CSS center display inline block?

This will horizontally center an inline-block element without needing to modify its parent's styles:

  display: inline-block;
  position: relative;
  // Move the element to the left by 50% of the container's width
  left: 50%; 
  // Calculates 50% of the element's width, and moves it by that
  // amount across the X-axis to the left
  transform: translateX(-50%);

Creating a new ArrayList in Java

Fixed the code for you:

ArrayList<Class> myArray= new ArrayList<Class>();

How can I create directory tree in C++/Linux?

So I need mkdirp() today, and found the solutions on this page overly complicated. Hence I wrote a fairly short snippet, that easily be copied in for others who stumble upon this thread an wonder why we need so many lines of code.

mkdirp.h

#ifndef MKDIRP_H
#define MKDIRP_H

#include <sys/stat.h>

#define DEFAULT_MODE      S_IRWXU | S_IRGRP |  S_IXGRP | S_IROTH | S_IXOTH

/** Utility function to create directory tree */
bool mkdirp(const char* path, mode_t mode = DEFAULT_MODE);

#endif // MKDIRP_H

mkdirp.cpp

#include <errno.h>

bool mkdirp(const char* path, mode_t mode) {
  // const cast for hack
  char* p = const_cast<char*>(path);

  // Do mkdir for each slash until end of string or error
  while (*p != '\0') {
    // Skip first character
    p++;

    // Find first slash or end
    while(*p != '\0' && *p != '/') p++;

    // Remember value from p
    char v = *p;

    // Write end of string at p
    *p = '\0';

    // Create folder from path to '\0' inserted at p
    if(mkdir(path, mode) == -1 && errno != EEXIST) {
      *p = v;
      return false;
    }

    // Restore path to it's former glory
    *p = v;
  }

  return true;
}

If you don't like const casting and temporarily modifying the string, just do a strdup() and free() it afterwards.

Windows 7, 64 bit, DLL problems

Just to confirm answers here, my resolution was to copy the DLL that was not loading AND the ocx file that accompanied it to the system32 folder, that resolved my issue.

Best way to get user GPS location in background in Android

Well Create a class extending Service ,this service will contain your Location listener class(Fused Location Provider) purpose of this service is to get location periodically , something like this

  public class LocationGetter extends Service {


    ......

    public class MyLocationListener implements GooglePlayServicesClient.ConnectionCallbacks,GooglePlayServicesClient.OnConnectionFailedListener,LocationListener, com.google.android.gms.location.LocationListener {

   //your fused Location provider code

    }

    ......

}

Then create a class extending Broadcast Receiver , such that the purpose of this broadcast Receiver is to check whether service is alive if not restart service even during phone ON/OFF ....

register receiver in ur activity , listen for broadcasts , unregeister receiver depending ur need...

How do I turn off PHP Notices?

I found this trick out recently. Whack an @ at the start of a line that may produce an warning/error.

As if by magic, they dissapear.

How to find the duration of difference between two dates in java?

Here is how the problem can solved in Java 8 just like the answer by shamimz.

Source : http://docs.oracle.com/javase/tutorial/datetime/iso/period.html

LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);

Period p = Period.between(birthday, today);
long p2 = ChronoUnit.DAYS.between(birthday, today);

System.out.println("You are " + p.getYears() + " years, " + p.getMonths() + " months, and " + p.getDays() + " days old. (" + p2 + " days total)");

The code produces output similar to the following:

You are 53 years, 4 months, and 29 days old. (19508 days total)

We have to use LocalDateTime http://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html to get hour,minute,second differences.

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

I'm loathe to add another answer to this already overcrowded question, but it might be of use to someone.

I found that if a "release" already had a build assigned when I uploaded a new one, clearing the existing build and attempting to select the new one always showed it as "processing".

However, if I removed the old build and saved then refreshed the page, the new build could be selected.

How to reset radiobuttons in jQuery so that none is checked

In versions of jQuery before 1.6 use:

$('input[name="correctAnswer"]').attr('checked', false);

In versions of jQuery after 1.6 you should use:

$('input[name="correctAnswer"]').prop('checked', false);

but if you are using 1.6.1+ you can use the first form (see note 2 below).

Note 1: it is important that the second argument be false and not "false" since "false" is not a falsy value. i.e.

if ("false") {
    alert("Truthy value. You will see an alert");
}

Note 2: As of jQuery 1.6.0, there are now two similar methods, .attr and .prop that do two related but slightly different things. If in this particular case, the advice provide above works if you use 1.6.1+. The above will not work with 1.6.0, if you are using 1.6.0, you should upgrade. If you want the details, keep reading.

Details: When working with straight HTML DOM elements, there are properties attached to the DOM element (checked, type, value, etc) which provide an interface to the running state of the HTML page. There is also the .getAttribute/.setAttribute interface which provides access to the HTML Attribute values as provided in the HTML. Before 1.6 jQuery blurred the distinction by providing one method, .attr, to access both types of values. jQuery 1.6+ provides two methods, .attr and .prop to get distinguish between these situations.

.prop allows you to set a property on a DOM element, while .attr allows you to set an HTML attribute value. If you are working with plain DOM and set the checked property, elem.checked, to true or false you change the running value (what the user sees) and the value returned tracks the on page state. elem.getAttribute('checked') however only returns the initial state (and returns 'checked' or undefined depending on the initial state from the HTML). In 1.6.1+ using .attr('checked', false) does both elem.removeAttribute('checked') and elem.checked = false since the change caused a lot of backwards compatibility issues and it can't really tell if you wanted to set the HTML attribute or the DOM property. See more information in the documentation for .prop.

Convert a video to MP4 (H.264/AAC) with ffmpeg

You need to compile ffmpeg with an AAC encoder. You can find one at AudioCoding.

How to make return key on iPhone make keyboard disappear?

Set the Delegate of the UITextField to your ViewController, add a referencing outlet between the File's Owner and the UITextField, then implement this method:

-(BOOL)textFieldShouldReturn:(UITextField *)textField 
{
   if (textField == yourTextField) 
   {
      [textField resignFirstResponder]; 
   }
   return NO;
}

How to exit from ForEach-Object in PowerShell

I found this question while looking for a way to have fine grained flow control to break from a specific block of code. The solution I settled on wasn't mentioned...

Using labels with the break keyword

From: about_break

A Break statement can include a label that lets you exit embedded loops. A label can specify any loop keyword, such as Foreach, For, or While, in a script.

Here's a simple example

:myLabel for($i = 1; $i -le 2; $i++) {
        Write-Host "Iteration: $i"
        break myLabel
}

Write-Host "After for loop"

# Results:
# Iteration: 1
# After for loop

And then a more complicated example that shows the results with nested labels and breaking each one.

:outerLabel for($outer = 1; $outer -le 2; $outer++) {

    :innerLabel for($inner = 1; $inner -le 2; $inner++) {
        Write-Host "Outer: $outer / Inner: $inner"
        #break innerLabel
        #break outerLabel
    }

    Write-Host "After Inner Loop"
}

Write-Host "After Outer Loop"

# Both breaks commented out
# Outer: 1 / Inner: 1
# Outer: 1 / Inner: 2
# After Inner Loop
# Outer: 2 / Inner: 1
# Outer: 2 / Inner: 2
# After Inner Loop
# After Outer Loop

# break innerLabel Results
# Outer: 1 / Inner: 1
# After Inner Loop
# Outer: 2 / Inner: 1
# After Inner Loop
# After Outer Loop

# break outerLabel Results
# Outer: 1 / Inner: 1
# After Outer Loop

You can also adapt it to work in other situations by wrapping blocks of code in loops that will only execute once.

:myLabel do {
    1..2 | % {

        Write-Host "Iteration: $_"
        break myLabel

    }
} while ($false)

Write-Host "After do while loop"

# Results:
# Iteration: 1
# After do while loop

ES6 export default with multiple functions referring to each other

tl;dr: baz() { this.foo(); this.bar() }

In ES2015 this construct:

var obj = {
    foo() { console.log('foo') }
}

is equal to this ES5 code:

var obj = {
    foo : function foo() { console.log('foo') }
}

exports.default = {} is like creating an object, your default export translates to ES5 code like this:

exports['default'] = {
    foo: function foo() {
        console.log('foo');
    },
    bar: function bar() {
        console.log('bar');
    },
    baz: function baz() {
        foo();bar();
    }
};

now it's kind of obvious (I hope) that baz tries to call foo and bar defined somewhere in the outer scope, which are undefined. But this.foo and this.bar will resolve to the keys defined in exports['default'] object. So the default export referencing its own methods shold look like this:

export default {
    foo() { console.log('foo') }, 
    bar() { console.log('bar') },
    baz() { this.foo(); this.bar() }
}

See babel repl transpiled code.

How can I make content appear beneath a fixed DIV element?

I just had this problem, and this was my solution:

#floatingMenu + * {
    margin-top: 35px;
}

Adjust for the height of your floatingMenu. If you don't know for sure that it's a div following then you can use * rather than div. This is all valid CSS2.

Request Monitoring in Chrome

Thanks all person who try to help in this post

I have ubuntu 13.10 and my chrome version is 34.0

For my situation this works

1.open developer tools in chrome(or use right click on your page and then select inspect element)
2.go to "Network" tab
3.find your ajax request in "Name Path" column 
4.click on the specific ajax link

now you should see a new Panel in front of you request

in this panel select "Response" tab

Git: can't undo local changes (error: path ... is unmerged)

git checkout foo/bar.txt

did you tried that? (without a HEAD keyword)

I usually revert my changes this way.

Save Javascript objects in sessionStorage

The solution is to stringify the object before calling setItem on the sessionStorage.

var user = {'name':'John'};
sessionStorage.setItem('user', JSON.stringify(user));
var obj = JSON.parse(sessionStorage.user);

Execute curl command within a Python script

You can use below code snippet

import shlex
import subprocess
import json

def call_curl(curl):
    args = shlex.split(curl)
    process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()
    return json.loads(stdout.decode('utf-8'))


if __name__ == '__main__':
    curl = '''curl - X
    POST - d
    '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}'
    http: // localhost: 8080 / firewall / rules / 0000000000000001 '''
    output = call_curl(curl)
    print(output)

With ' N ' no of nodes, how many different Binary and Binary Search Trees possible?

Eric Lippert recently had a very in-depth series of blog posts about this: "Every Binary Tree There Is" and "Every Tree There Is" (plus some more after that).

In answer to your specific question, he says:

The number of binary trees with n nodes is given by the Catalan numbers, which have many interesting properties. The nth Catalan number is determined by the formula (2n)! / (n+1)!n!, which grows exponentially.

What's HTML character code 8203?

If you want to search for these invisible characters in your editor and make them visible, you can use a Regular Expression searching for non-ascii characters. Try searching for [^\x00-\x7F]. Tested in IntelliJ IDEA.

Javascript Cookie with no expiration date

You can do as the example on Mozilla docs:

 document.cookie = "someCookieName=true; expires=Fri, 31 Dec 9999 23:59:59 GMT";

P.S

Of course, there will be an issue if humanity still uses your code on the first minute of year 10000 :)

How do I escape the wildcard/asterisk character in bash?

If you don't want to bother with weird expansions from bash you can do this

me$ FOO="BAR \x2A BAR"   # 2A is hex code for *
me$ echo -e $FOO
BAR * BAR
me$ 

Explanation here why using -e option of echo makes life easier:

Relevant quote from man here:

SYNOPSIS
   echo [SHORT-OPTION]... [STRING]...
   echo LONG-OPTION

DESCRIPTION
   Echo the STRING(s) to standard output.

   -n     do not output the trailing newline

   -e     enable interpretation of backslash escapes

   -E     disable interpretation of backslash escapes (default)

   --help display this help and exit

   --version
          output version information and exit

   If -e is in effect, the following sequences are recognized:

   \\     backslash

   ...

   \0NNN  byte with octal value NNN (1 to 3 digits)

   \xHH   byte with hexadecimal value HH (1 to 2 digits)

For the hex code you can check man ascii page (first line in octal, second decimal, third hex):

   051   41    29    )                           151   105   69    i
   052   42    2A    *                           152   106   6A    j
   053   43    2B    +                           153   107   6B    k

How can I concatenate a string and a number in Python?

Since Python is a strongly typed language, concatenating a string and an integer as you may do in Perl makes no sense, because there's no defined way to "add" strings and numbers to each other.

Explicit is better than implicit.

...says "The Zen of Python", so you have to concatenate two string objects. You can do this by creating a string from the integer using the built-in str() function:

>>> "abc" + str(9)
'abc9'

Alternatively use Python's string formatting operations:

>>> 'abc%d' % 9
'abc9'

Perhaps better still, use str.format():

>>> 'abc{0}'.format(9)
'abc9'

The Zen also says:

There should be one-- and preferably only one --obvious way to do it.

Which is why I've given three options. It goes on to say...

Although that way may not be obvious at first unless you're Dutch.

Global and local variables in R

Variables declared inside a function are local to that function. For instance:

foo <- function() {
    bar <- 1
}
foo()
bar

gives the following error: Error: object 'bar' not found.

If you want to make bar a global variable, you should do:

foo <- function() {
    bar <<- 1
}
foo()
bar

In this case bar is accessible from outside the function.

However, unlike C, C++ or many other languages, brackets do not determine the scope of variables. For instance, in the following code snippet:

if (x > 10) {
    y <- 0
}
else {
    y <- 1
}

y remains accessible after the if-else statement.

As you well say, you can also create nested environments. You can have a look at these two links for understanding how to use them:

  1. http://stat.ethz.ch/R-manual/R-devel/library/base/html/environment.html
  2. http://stat.ethz.ch/R-manual/R-devel/library/base/html/get.html

Here you have a small example:

test.env <- new.env()

assign('var', 100, envir=test.env)
# or simply
test.env$var <- 100

get('var') # var cannot be found since it is not defined in this environment
get('var', envir=test.env) # now it can be found

EditText request focus

It has worked for me as follows.

ed1.requestFocus();

            return; //Faça um return para retornar o foco

Can I run multiple programs in a Docker container?

I agree with the other answers that using two containers is preferable, but if you have your heart set on bunding multiple services in a single container you can use something like supervisord.

in Hipache for instance, the included Dockerfile runs supervisord, and the file supervisord.conf specifies for both hipache and redis-server to be run.

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

There's a huge difference. As has been mentioned, <%@ include is a static include, <jsp:include is a dynamic include. Think of it as a difference between a macro and a function call (if you are familiar with those terms). Another way of putting it, a static include is exactly the same thing as copy-pasting the exact content of the included file (the "code") at the location of the <%@ include statement (which is exactly what the JSP compiler will do.

A dynamic include will make a request (using the request dispatcher) that will execute the indicated page and then include the output from the page in the output of the calling page, in place of the <jsp:include statement.

The big difference here is that with a dynamic include, the included page will execute in it's own pageContext. And since it's a request, you can send parameters to the page the same way you can send parameters along with any other request. A static include, on the other hand, is just a piece of code that will execute inside the context of the calling page. If you statically include the same file more than once, the code in that file will exist in multiple locations on the calling page so something like

<%
int i = 0;
%>

would generate a compiler error (since the same variable can't be declared more than once).

"This SqlTransaction has completed; it is no longer usable."... configuration error?

Had the exact same problem and just could not find the right solution. Hope this helps somebody.

I have an .NET Core 3.1 WebApi with EF Core. Upon receiving multiple calls at the same time, the applications was trying to add and save changes to the database at the same time.

In my case the problem was that the table that the data would be saved in did not have a primary key set.

Somehow EF Core missed when the migration was ran from the application that the ID in the model was supposed to be a primary key.

I found the problem by opening the SQL Profiler and seeing that all transactions was successfully submitted to the database (from the application) but only one new row was created. The profiler also showed that some type of deadlock was happening but I couldn't see much more in the trace logs of the profiler. On further inspection I noticed that the primary key identifier was missing on the column "Id".

The exceptions I got from my application was:

This SqlTransaction has completed; it is no longer usable.

and/or

An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseSqlServer' call.

Disable a Maven plugin defined in a parent POM

I know this thread is really old but the solution from @Ivan Bondarenko helped me in my situation.

I had the following in my pom.xml.

<build>
    ...
    <plugins>
         <plugin>
                <groupId>com.consol.citrus</groupId>
                <artifactId>citrus-remote-maven-plugin</artifactId>
                <version>${citrus.version}</version>
                <executions>
                    <execution>
                        <id>generate-citrus-war</id>
                        <goals>
                            <goal>test-war</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
    </plugins>
</build>

What I wanted, was to disable the execution of generate-citrus-war for a specific profile and this was the solution:

<profile>
    <id>it</id>
    <build>
        <plugins>
            <plugin>
                <groupId>com.consol.citrus</groupId>
                <artifactId>citrus-remote-maven-plugin</artifactId>
                <version>${citrus.version}</version>
                <executions>
                    <!-- disable generating the war for this profile -->
                    <execution>
                        <id>generate-citrus-war</id>
                        <phase/>
                    </execution>

                    <!-- do something else -->
                    <execution>
                        ...
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</profile>

Check folder size in Bash

You can do:

du -h your_directory

which will give you the size of your target directory.

If you want a brief output, du -hcs your_directory is nice.

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

perhaps this comes too late, but still it could be nice to "document it" for others out there.

I received the same error after experimenting and testing with Remote Desktop Services on a MS Server 2012 with MS SQL Server 2012.

During the Remote Desktop Services install one is asked to create a (local) certificate, and so I did. After finishing the test/experiments I removed the Remote Desktop Services. That's when this error appeared (I cannot say whether the error occured during the test with RDS, I don't remember if I used/tried the SQL Connection during the RDS test).

I am not sure how to solve this since the default certificate does not work for me, but the "RDS" certificate does.

BTW, the certificates are found in App: "SQL Server Configuration Manager" -> "SQL Server Network Configuration" -> Right click: "Protocols for " -> Select "Properties" -> Tab "Certificate"

My default SQL Certificate is named: ConfigMgr SQL Server Identification Certificate, has expiration date: 2114-06-09.

Hope this can give a hint to others.

/Kim

Read all files in a folder and apply a function to each data frame

usually i don't use for loop in R, but here is my solution using for loops and two packages : plyr and dostats

plyr is on cran and you can download dostats on https://github.com/halpo/dostats (may be using install_github from Hadley devtools package)

Assuming that i have your first two data.frame (Df.1 and Df.2) in csv files, you can do something like this.

require(plyr)
require(dostats)

files <- list.files(pattern = ".csv")


for (i in seq_along(files)) {

    assign(paste("Df", i, sep = "."), read.csv(files[i]))

    assign(paste(paste("Df", i, sep = ""), "summary", sep = "."), 
           ldply(get(paste("Df", i, sep = ".")), dostats, sum, min, mean, median, max))

}

Here is the output

R> Df1.summary
  .id sum min   mean median max
1   A  34   4 5.6667    5.5   8
2   B  22   1 3.6667    3.0   9
R> Df2.summary
  .id sum min   mean median max
1   A  21   1 3.5000    3.5   6
2   B  16   1 2.6667    2.5   5

Prime numbers between 1 to 100 in C Programming Language

#include<stdio.h>
int main()
{
    int a,b,i,c,j;
    printf("\n Enter the two no. in between you want to check:");
    scanf("%d%d",&a,&c);
    printf("%d-%d\n",a,c);
    for(j=a;j<=c;j++)
    {
        b=0;
        for(i=1;i<=c;i++)
        {
            if(j%i==0)
            {
                 b++;
            }
        }
        if(b==2)
        {
            printf("\nPrime number:%d\n",j);
        }
        else
        {
            printf("\n\tNot prime:%d\n",j);
        }
    }
}

How to rename a class and its corresponding file in Eclipse?

Right click on the class->select Refactor->Rename

Get ID of element that called a function

You can use 'this' in event handler:

document.getElementById("preview").onmouseover = function() {
    alert(this.id);
}

Or pass event object to handler as follows:

document.getElementById("preview").onmouseover = function(evt) {
    alert(evt.target.id);
}

It's recommended to use attachEvent(for IE < 9)/addEventListener(IE9 and other browsers) to attach events. Example above is for brevity.

function myHandler(evt) {
    alert(evt.target.id);
}

var el = document.getElementById("preview");
if (el.addEventListener){
    el.addEventListener('click', myHandler, false); 
} else if (el.attachEvent){
    el.attachEvent('onclick', myHandler);
}

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

Short ES6 code

const convertFrom24To12Format = (time24) => {
  const [sHours, minutes] = time24.match(/([0-9]{1,2}):([0-9]{2})/).slice(1);
  const period = +sHours < 12 ? 'AM' : 'PM';
  const hours = +sHours % 12 || 12;

  return `${hours}:${minutes} ${period}`;
}
const convertFrom12To24Format = (time12) => {
  const [sHours, minutes, period] = time12.match(/([0-9]{1,2}):([0-9]{2}) (AM|PM)/).slice(1);
  const PM = period === 'PM';
  const hours = (+sHours % 12) + (PM ? 12 : 0);

  return `${('0' + hours).slice(-2)}:${minutes}`;
}

What are "named tuples" in Python?

What is namedtuple ?

As the name suggests, namedtuple is a tuple with name. In standard tuple, we access the elements using the index, whereas namedtuple allows user to define name for elements. This is very handy especially processing csv (comma separated value) files and working with complex and large dataset, where the code becomes messy with the use of indices (not so pythonic).

How to use them ?

>>>from collections import namedtuple
>>>saleRecord = namedtuple('saleRecord','shopId saleDate salesAmout totalCustomers')
>>>
>>>
>>>#Assign values to a named tuple 
>>>shop11=saleRecord(11,'2015-01-01',2300,150) 
>>>shop12=saleRecord(shopId=22,saleDate="2015-01-01",saleAmout=1512,totalCustomers=125)

Reading

>>>#Reading as a namedtuple
>>>print("Shop Id =",shop12.shopId)
12
>>>print("Sale Date=",shop12.saleDate)
2015-01-01
>>>print("Sales Amount =",shop12.salesAmount)
1512
>>>print("Total Customers =",shop12.totalCustomers)
125

Interesting Scenario in CSV Processing :

from csv import reader
from collections import namedtuple

saleRecord = namedtuple('saleRecord','shopId saleDate totalSales totalCustomers')
fileHandle = open("salesRecord.csv","r")
csvFieldsList=csv.reader(fileHandle)
for fieldsList in csvFieldsList:
    shopRec = saleRecord._make(fieldsList)
    overAllSales += shopRec.totalSales;

print("Total Sales of The Retail Chain =",overAllSales)

Parse JSON String to JSON Object in C#.NET

Since you mentioned that you are using Newtonsoft.dll you can convert a JSON string to an object by using its facilities:

MyClass myClass = JsonConvert.DeserializeObject<MyClass>(your_json_string);

[Serializable]
public class MyClass
{
    public string myVar {get; set;}
    etc.
}

Activity has leaked window that was originally added

This problem arises when trying to show a Dialog after you've exited an Activity.

I just solved this problem just by writing down the following code:

@Override
public void onDestroy(){
    super.onDestroy();
    if ( progressDialog!=null && progressDialog.isShowing() ){
        progressDialog.cancel();
    }
}

Basically, from which class you started progressDialog, override onDestroy method and do this way. It solved "Activity has leaked window" problem.

Creating dummy variables in pandas for python

Handling categorical features scikit-learn expects all features to be numeric. So how do we include a categorical feature in our model?

Ordered categories: transform them to sensible numeric values (example: small=1, medium=2, large=3) Unordered categories: use dummy encoding (0/1) What are the categorical features in our dataset?

Ordered categories: weather (already encoded with sensible numeric values) Unordered categories: season (needs dummy encoding), holiday (already dummy encoded), workingday (already dummy encoded) For season, we can't simply leave the encoding as 1 = spring, 2 = summer, 3 = fall, and 4 = winter, because that would imply an ordered relationship. Instead, we create multiple dummy variables:

# An utility function to create dummy variable
`def create_dummies( df, colname ):
col_dummies = pd.get_dummies(df[colname], prefix=colname)
col_dummies.drop(col_dummies.columns[0], axis=1, inplace=True)
df = pd.concat([df, col_dummies], axis=1)
df.drop( colname, axis = 1, inplace = True )
return df`

How do I get extra data from intent on Android?

Just a suggestion:

Instead of using "id" or "name" in your i.putExtra("id".....), I would suggest, when it makes sense, using the current standard fields that can be used with putExtra(), i.e. Intent.EXTRA_something.

A full list can be found at Intent (Android Developers).

How do I make a textbox that only accepts numbers?

The simplest and crudest way is to use a combobox instead of textbox with ReadOnly. But of course its only useful if you are expecting the user to use a decent and reasonable set of whole numbers, not try to touch infinity.

Difference between natural join and inner join

difference is that int the inner(equi/default)join and natural join that in the natuarl join common column win will be display in single time but inner/equi/default/simple join the common column will be display double time.

Apache is downloading php files instead of displaying them

After updating PHP to 7.3, PHP scripts where run with www-data instead of $USER like before.

I needed to reinstall and activate PHP-FPM :

sudo apt-get install php-fpm
sudo a2enmod proxy_fcgi setenvif
sudo service apache2 restart
sudo a2enconf php7.3-fpm
sudo service apache2 restart

To ensure everything was ok for Virtualmin, i used the Re-Check Configuration wizard /virtual-server/check.cgi, under Vitualmin/System Settings.

After that, Apache/PHP was downloading php files instead of running them. So i needed to edit /etc/apache2/mods-available/php7.3.conf to comment the row SetHandler application/x-httpd-php like below :

<FilesMatch ".+\.ph(ar|p|tml)$">
#    SetHandler application/x-httpd-php
</FilesMatch>

After restarting Apache, it solved my issue, hope this help.

Take care of browser cache too.

My system :

Ubuntu          16.04.6 LTS
Webmin version      1.932
Usermin version     1.780
Virtualmin version  6.08
Apache version      2.4.41
PHP versions        7.3.12
PHP-FPM         7.3.12 Server

BehaviorSubject vs Observable?

The Observable object represents a push based collection.

The Observer and Observable interfaces provide a generalized mechanism for push-based notification, also known as the observer design pattern. The Observable object represents the object that sends notifications (the provider); the Observer object represents the class that receives them (the observer).

The Subject class inherits both Observable and Observer, in the sense that it is both an observer and an observable. You can use a subject to subscribe all the observers, and then subscribe the subject to a backend data source

var subject = new Rx.Subject();

var subscription = subject.subscribe(
    function (x) { console.log('onNext: ' + x); },
    function (e) { console.log('onError: ' + e.message); },
    function () { console.log('onCompleted'); });

subject.onNext(1);
// => onNext: 1

subject.onNext(2);
// => onNext: 2

subject.onCompleted();
// => onCompleted

subscription.dispose();

More on https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/subjects.md

Fatal error: Call to a member function bind_param() on boolean

Sometimes, it is also because of a wrong table name or column name in the prepare statement.

See this.

Rollback a Git merge

git revert -m 1 88113a64a21bf8a51409ee2a1321442fd08db705

But may have unexpected side-effects. See --mainline parent-number option in git-scm.com/docs/git-revert

Perhaps a brute but effective way would be to check out the left parent of that commit, make a copy of all the files, checkout HEAD again, and replace all the contents with the old files. Then git will tell you what is being rolled back and you create your own revert commit :) !

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

HTML img onclick Javascript

Developers also take care about accessibility.

Do not use onClick on images without defining the ARIA role.

Non-interactive HTML elements and non-interactive ARIA roles indicate content and containers in the user interface. A non-interactive element does not support event handlers (mouse and key handlers).

The developer and designers are responsible for providing the expected behavior of an element that the role suggests it would have: focusability and key press support. More info see WAI-ARIA Authoring Practices Guide - Design Patterns and Widgets.

tldr; this is how it should be done:

  <img
    src="pond1.jpg"
    alt="pic id code"
    onClick="window.open(this.src)"
    role="button"
    tabIndex="0"
  />

What is the difference between HTTP and REST?

HTTP is a communications protocol that transports messages over a network. SOAP is a protocol to exchange XML-based messages that can use HTTP to transport those messages. Rest is a protocol to exchange any(XML or JSON) messages that can use HTTP to transport those messages.

Get specific ArrayList item

Time to familiarize yourself with the ArrayList API and more:

ArrayList at Java 6 API Documentation

For your immediate question:

mainList.get(3);

What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

Shortcut way: (windows xp)

1) click Start > run > services.msc

2) Scroll down to 'Windows Presentation Foundation Font Cache 4.0.0.0' and then right click and select properties

How to convert flat raw disk image to vmdk for virtualbox or vmplayer?

Since the question mentions VirtualBox, this one works currently:

VBoxManage convertfromraw imagefile.dd vmdkname.vmdk --format VMDK

Run it without arguments for a few interesting details (notably the --variant flag):

VBoxManage convertfromraw

Printing to the console in Google Apps Script?

Answering the OP questions

A) What do I not understand about how the Google Apps Script console works with respect to printing so that I can see if my code is accomplishing what I'd like?

The code on .gs files of a Google Apps Script project run on the server rather than on the web browser. The way to log messages was to use the Class Logger.

B) Is it a problem with the code?

As the error message said, the problem was that console was not defined but nowadays the same code will throw other error:

ReferenceError: "playerArray" is not defined. (line 12, file "Code")

That is because the playerArray is defined as local variable. Moving the line out of the function will solve this.

var playerArray = [];

function addplayerstoArray(numplayers) {
  for (i=0; i<numplayers; i++) {
    playerArray.push(i);
  }
}  

addplayerstoArray(7);

console.log(playerArray[3])

Now that the code executes without throwing errors, instead to look at the browser console we should look at the Stackdriver Logging. From the Google Apps Script editor UI click on View > Stackdriver Logging.

Addendum

On 2017 Google released to all scripts Stackdriver Logging and added the Class Console, so including something like console.log('Hello world!') will not throw an error but the log will be on Google Cloud Platform Stackdriver Logging Service instead of the browser console.

From Google Apps Script Release Notes 2017

June 23, 2017

Stackdriver Logging has been moved out of Early Access. All scripts now have access to Stackdriver logging.

From Logging > Stackdriver logging

The following example shows how to use the console service to log information in Stackdriver.

function measuringExecutionTime() {
  // A simple INFO log message, using sprintf() formatting.
  console.info('Timing the %s function (%d arguments)', 'myFunction', 1);

  // Log a JSON object at a DEBUG level. The log is labeled
  // with the message string in the log viewer, and the JSON content
  // is displayed in the expanded log structure under "structPayload".
  var parameters = {
      isValid: true,
      content: 'some string',
      timestamp: new Date()
  };
  console.log({message: 'Function Input', initialData: parameters});

  var label = 'myFunction() time';  // Labels the timing log entry.
  console.time(label);              // Starts the timer.
  try {
    myFunction(parameters);         // Function to time.
  } catch (e) {
    // Logs an ERROR message.
    console.error('myFunction() yielded an error: ' + e);
  }
  console.timeEnd(label);      // Stops the timer, logs execution duration.
}

Changing default encoding of Python?

Starting with PyDev 3.4.1, the default encoding is not being changed anymore. See this ticket for details.

For earlier versions a solution is to make sure PyDev does not run with UTF-8 as the default encoding. Under Eclipse, run dialog settings ("run configurations", if I remember correctly); you can choose the default encoding on the common tab. Change it to US-ASCII if you want to have these errors 'early' (in other words: in your PyDev environment). Also see an original blog post for this workaround.

How do I print an IFrame from javascript in Safari/Chrome

In addition to Andrew's and Max's solutions, using iframe.focus() resulted in printing parent frame instead of printing only child iframe in IE8. Changing that line fixed it:

function printIframe(id)
{
    var iframe = document.frames ? document.frames[id] : document.getElementById(id);
    var ifWin = iframe.contentWindow || iframe;
    ifWin.focus();
    ifWin.printPage();
    return false;
}

html5 input for money/currency

We had the same problem for accepting monetary values for Euro, since <input type="number" /> can't display Euro decimal and comma format.

We came up with a solution, to use <input type="number" /> for user input. After user types in the value, we format it and display as a Euro format by just switching to <input type="text" />. This is a Javascript solution though, cuz you need a condition to decide between "user is typing" and "display to user" modes.

Here the link with Visuals to our solution: Input field type "Currency" problem solved

Hope this helps in some way!

How to overlay image with color in CSS?

#header.overlay {
    background-color: SlateGray;
    position:relative;
    width: 100%;
    height: 100%;
    opacity: 0.20;
    -moz-opacity: 20%;
    -webkit-opacity: 20%;
    z-index: 2;
}

Something like this. Just add the overlay class to the header, obviously.

start MySQL server from command line on Mac OS Lion

If it's installed with homebrew try just typing down mysql.server in terminal and that should be it. AFAIK it executable will be under /usr/local/bin/mysql.server.

If not you can always run following "locate mysql.server" which will tell you where to find such file.

HttpClient not supporting PostAsJsonAsync method C#

I know this reply is too late, I had the same issue and i was adding the System.Net.Http.Formatting.Extension Nuget, after checking here and there I found that the Nuget is added but the System.Net.Http.Formatting.dll was not added to the references, I just reinstalled the Nuget

Preventing form resubmission

Try tris:

function prevent_multi_submit($excl = "validator") {
    $string = "";
    foreach ($_POST as $key => $val) {
    // this test is to exclude a single variable, f.e. a captcha value
    if ($key != $excl) {
        $string .= $key . $val;
    }
    }
    if (isset($_SESSION['last'])) {
    if ($_SESSION['last'] === md5($string)) {
        return false;
    } else {
        $_SESSION['last'] = md5($string);
        return true;
    }
    } else {
    $_SESSION['last'] = md5($string);
    return true;
    }
}

How to use / example:

if (isset($_POST)) {
    if ($_POST['field'] != "") { // place here the form validation and other controls
    if (prevent_multi_submit()) { // use the function before you call the database or etc
        mysql_query("INSERT INTO table..."); // or send a mail like...
        mail($mailto, $sub, $body); // etc
    } else {
        echo "The form is already processed";
    }
    } else {
    // your error about invalid fields
    }
}

Font: https://www.tutdepot.com/prevent-multiple-form-submission/

Create Excel file in Java

I've created the API "generator-excel" to create an Excel file, below the dependecy:

<dependency>
  <groupId>com.github.bld-commons.excel</groupId>
  <artifactId>generator-excel</artifactId>
  <version>3.1.0</version>
</dependency>

This library can to configure the styles, the functions, the charts, the pivot table and etc. through a series of annotations.
You can write rows by getting data from a datasource trough a query with or without parameters.
Below an example to develop

  1. I created 2 classes that represents the row of the table.
  2. package bld.generator.report.junit.entity;
        
        import java.util.Date;
        
        import org.apache.poi.ss.usermodel.HorizontalAlignment;
        
        import bld.generator.report.excel.RowSheet;
        import bld.generator.report.excel.annotation.ExcelCellLayout;
        import bld.generator.report.excel.annotation.ExcelColumn;
        import bld.generator.report.excel.annotation.ExcelDate;
        import bld.generator.report.excel.annotation.ExcelImage;
        import bld.generator.report.excel.annotation.ExcelRowHeight;
        
        @ExcelRowHeight(height = 3)
        public class UtenteRow implements RowSheet {
            
            @ExcelColumn(columnName = "Id", indexColumn = 0)
            @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT)
            private Integer idUtente; 
            @ExcelColumn(columnName = "Nome", indexColumn = 2)
            @ExcelCellLayout
            private String nome; 
            @ExcelColumn(columnName = "Cognome", indexColumn = 1)
            @ExcelCellLayout
            private String cognome;
            @ExcelColumn(columnName = "Data di nascita", indexColumn = 3)
            @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.CENTER)
            @ExcelDate
            private Date dataNascita;
            @ExcelColumn(columnName = "Immagine", indexColumn = 4)
            @ExcelCellLayout
            @ExcelImage(resizeHeight = 0.7, resizeWidth = 0.6)
            private byte[] image;   
            
            @ExcelColumn(columnName = "Path", indexColumn = 5)
            @ExcelCellLayout
            @ExcelImage(resizeHeight = 0.7, resizeWidth = 0.6)
            private String path;    
            
        
            public UtenteRow() {
            }
        
        
            public UtenteRow(Integer idUtente, String nome, String cognome, Date dataNascita) {
                super();
                this.idUtente = idUtente;
                this.nome = nome;
                this.cognome = cognome;
                this.dataNascita = dataNascita;
            }
        
        
            public Integer getIdUtente() {
                return idUtente;
            }
        
        
            public void setIdUtente(Integer idUtente) {
                this.idUtente = idUtente;
            }
        
        
            public String getNome() {
                return nome;
            }
        
        
            public void setNome(String nome) {
                this.nome = nome;
            }
        
        
            public String getCognome() {
                return cognome;
            }
        
        
            public void setCognome(String cognome) {
                this.cognome = cognome;
            }
        
        
            public Date getDataNascita() {
                return dataNascita;
            }
        
        
            public void setDataNascita(Date dataNascita) {
                this.dataNascita = dataNascita;
            }
        
        
            public byte[] getImage() {
                return image;
            }
        
        
            public String getPath() {
                return path;
            }
        
        
            public void setImage(byte[] image) {
                this.image = image;
            }
        
        
            public void setPath(String path) {
                this.path = path;
            }
        
        }
    

    package bld.generator.report.junit.entity;
    
    import org.apache.poi.ss.usermodel.DataConsolidateFunction;
    import org.apache.poi.ss.usermodel.HorizontalAlignment;
    
    import bld.generator.report.excel.RowSheet;
    import bld.generator.report.excel.annotation.ExcelCellLayout;
    import bld.generator.report.excel.annotation.ExcelColumn;
    import bld.generator.report.excel.annotation.ExcelFont;
    import bld.generator.report.excel.annotation.ExcelSubtotal;
    import bld.generator.report.excel.annotation.ExcelSubtotals;
    
    @ExcelSubtotals(labelTotalGroup = "Total",endLabel = "total")
    public class SalaryRow implements RowSheet {
    
        @ExcelColumn(columnName = "Name", indexColumn = 0)
        @ExcelCellLayout
        private String name;
        @ExcelColumn(columnName = "Amount", indexColumn = 1)
        @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT)
        @ExcelSubtotal(dataConsolidateFunction = DataConsolidateFunction.SUM,excelCellLayout = @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT,font=@ExcelFont(bold = true)))
        private Double amount;
        
        public SalaryRow() {
            super();
        }
        public SalaryRow(String name, Double amount) {
            super();
            this.name = name;
            this.amount = amount;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Double getAmount() {
            return amount;
        }
        public void setAmount(Double amount) {
            this.amount = amount;
        }
        
    }
    
  3. I created 2 class that represents the sheets.
  4. package bld.generator.report.junit.entity;
    
    import javax.validation.constraints.Size;
    
    import bld.generator.report.excel.QuerySheetData;
    import bld.generator.report.excel.annotation.ExcelHeaderLayout;
    import bld.generator.report.excel.annotation.ExcelMarginSheet;
    import bld.generator.report.excel.annotation.ExcelQuery;
    import bld.generator.report.excel.annotation.ExcelSheetLayout;
    
    @ExcelSheetLayout
    @ExcelHeaderLayout
    @ExcelMarginSheet(bottom = 1.5, left = 1.5, right = 1.5, top = 1.5)
    @ExcelQuery(select = "SELECT id_utente, nome, cognome, data_nascita,image,path "
            + "FROM utente "
            + "WHERE cognome=:cognome "
            + "order by cognome,nome")
    public class UtenteSheet extends QuerySheetData<UtenteRow> {
        
    
        public UtenteSheet(@Size(max = 31) String sheetName) {
            super(sheetName);
        }
    
        
    }
    

    package bld.generator.report.junit.entity;
    
    import javax.validation.constraints.Size;
    
    import bld.generator.report.excel.SheetData;
    import bld.generator.report.excel.annotation.ExcelHeaderLayout;
    import bld.generator.report.excel.annotation.ExcelMarginSheet;
    import bld.generator.report.excel.annotation.ExcelSheetLayout;
    @ExcelSheetLayout
    @ExcelHeaderLayout
    @ExcelMarginSheet(bottom = 1.5,left = 1.5,right = 1.5,top = 1.5)
    public class SalarySheet extends SheetData<SalaryRow> {
    
        public SalarySheet(@Size(max = 31) String sheetName) {
            super(sheetName);
        }
    
    }
    
  5. Class test, in the test function there are antoher sheets
  6. package bld.generator.report.junit;
    
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import java.util.List;
    
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    
    import bld.generator.report.excel.BaseSheet;
    import bld.generator.report.excel.GenerateExcel;
    import bld.generator.report.excel.data.ReportExcel;
    import bld.generator.report.junit.entity.AutoreLibriSheet;
    import bld.generator.report.junit.entity.CasaEditrice;
    import bld.generator.report.junit.entity.GenereSheet;
    import bld.generator.report.junit.entity.SalaryRow;
    import bld.generator.report.junit.entity.SalarySheet;
    import bld.generator.report.junit.entity.TotaleAutoreLibriRow;
    import bld.generator.report.junit.entity.TotaleAutoreLibriSheet;
    import bld.generator.report.junit.entity.UtenteSheet;
    import bld.generator.report.utils.ExcelUtils;
    
    /**
     * The Class ReportTest.
     */
    @RunWith(SpringRunner.class)
    @SpringBootTest
    @ConfigurationProperties
    @ComponentScan(basePackages = {"bld.generator","bld.read"})
    @EnableTransactionManagement
    public class ReportTestJpa {
    
        /** The Constant PATH_FILE. */
        private static final String PATH_FILE = "/mnt/report/";
    
        /** The generate excel. */
        @Autowired
        private GenerateExcel generateExcel;
    
        /**
         * Sets the up.
         *
         * @throws Exception the exception
         */
        @Before
        public void setUp() throws Exception {
        }
    
        /**
         * Test.
         *
         * @throws Exception the exception
         */
        @Test
        public void test() throws Exception {
            List<BaseSheet> listBaseSheet = new ArrayList<>();
            
            UtenteSheet utenteSheet=new UtenteSheet("Utente");
            utenteSheet.getMapParameters().put("cognome", "Rossi");
            listBaseSheet.add(utenteSheet);
            
            CasaEditrice casaEditrice = new CasaEditrice("Casa Editrice","Mondadori", new GregorianCalendar(1955, Calendar.MAY, 10), "Roma", "/home/francesco/Documents/git-project/dev-excel/linux.jpg","Drammatico");
            listBaseSheet.add(casaEditrice);
            
            
            AutoreLibriSheet autoreLibriSheet = new AutoreLibriSheet("Libri d'autore","Test label");
            TotaleAutoreLibriSheet totaleAutoreLibriSheet=new TotaleAutoreLibriSheet();
            totaleAutoreLibriSheet.getListRowSheet().add(new TotaleAutoreLibriRow("Totale"));
            autoreLibriSheet.setSheetFunctionsTotal(totaleAutoreLibriSheet);
            listBaseSheet.add(autoreLibriSheet);
            GenereSheet genereSheet=new GenereSheet("Genere");
            listBaseSheet.add(genereSheet);
            SalarySheet salarySheet=new SalarySheet("salary");
            salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
            salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
            salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
            salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
            salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
            salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
            salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
            salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
            listBaseSheet.add(salarySheet);
            ReportExcel excel = new ReportExcel("Mondadori JPA", listBaseSheet);
    
            byte[] byteReport = this.generateExcel.createFileXlsx(excel);
    
            ExcelUtils.writeToFile(PATH_FILE,excel.getTitle(), ".xlsx", byteReport);
    
        }
    
        
    
    }
    
  7. Application yaml
  8. logging:
      level:
        root: WARN
        org:
          springframework:
            web: DEBUG
          hibernate: ERROR
    
    
    
    spring:
      datasource:
        url: jdbc:postgresql://localhost:5432/excel_db
        username: ${EXCEL_USER_DB}
        password: ${EXCEL_PASSWORD_DB}
      jpa:
        show-sql: true
        properties:
          hibernate:
            default_schema: public
            jdbc:
              lob:
                non_contextual_creation: true 
            format_sql: true    
            ddl-auto: auto
        database-platform: org.hibernate.dialect.PostgreSQLDialect
        generate-ddl: true
    

below the link of the project on github:

WPF: simple TextBox data binding

Name2 is a field. WPF binds only to properties. Change it to:

public string Name2 { get; set; }

Be warned that with this minimal implementation, your TextBox won't respond to programmatic changes to Name2. So for your timer update scenario, you'll need to implement INotifyPropertyChanged:

partial class Window1 : Window, INotifyPropertyChanged
{
  public event PropertyChangedEventHandler PropertyChanged;

  protected void OnPropertyChanged(string propertyName)
  {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }

  private string _name2;

  public string Name2
  {
    get { return _name2; }
    set
    {
      if (value != _name2)
      {
         _name2 = value;
         OnPropertyChanged("Name2");
      }
    }
  }
}

You should consider moving this to a separate data object rather than on your Window class.

Android ListView headers

What I did to make the Date (e.g December 01, 2016) as header. I used the StickyHeaderListView library

https://github.com/emilsjolander/StickyListHeaders

Convert the date to long in millis [do not include the time] and make it as the header Id.

@Override
public long getHeaderId(int position) {
    return <date in millis>;
}

How to know a Pod's own IP address from inside a container in the Pod?

kubectl get pods -o wide

Give you a list of pods with name, status, ip, node...

TypeError: expected a character buffer object - while trying to save integer to textfile

Have you checked the docstring of write()? It says:

write(str) -> None. Write string str to file.

Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.

So you need to convert y to str first.

Also note that the string will be written at the current position which will be at the end of the file, because you'll already have read the old value. Use f.seek(0) to get to the beginning of the file.`

Edit: As for the IOError, this issue seems related. A cite from there:

For the modes where both read and writing (or appending) are allowed (those which include a "+" sign), the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a reading operation followed by a writing operation or a writing operation followed by a reading operation.

So, I suggest you try f.seek(0) and maybe the problem goes away.

How do I import .sql files into SQLite 3?

From a sqlite prompt:

sqlite> .read db.sql

Or:

cat db.sql | sqlite3 database.db

Also, your SQL is invalid - you need ; on the end of your statements:

create table server(name varchar(50),ipaddress varchar(15),id init);
create table client(name varchar(50),ipaddress varchar(15),id init);

Select a Column in SQL not in Group By

You can join the table on itself to get the PK:

Select cpe1.PK, cpe2.MaxDate, cpe1.fmgcms_cpeclaimid 
from Filteredfmgcms_claimpaymentestimate cpe1
INNER JOIN
(
    select MAX(createdon) As MaxDate, fmgcms_cpeclaimid 
    from Filteredfmgcms_claimpaymentestimate
    group by fmgcms_cpeclaimid
) cpe2
    on cpe1.fmgcms_cpeclaimid = cpe2.fmgcms_cpeclaimid
    and cpe1.createdon = cpe2.MaxDate
where cpe1.createdon < 'reportstartdate'

How do I set Tomcat Manager Application User Name and Password for NetBeans?

I case of tomcat 7 the role has changed from manager to manager-gui so set it as below in the tomcat-user.xml file.

enter image description here

MySQL LIMIT on DELETE statement

simply use

DELETE FROM test WHERE 1= 1 LIMIT 10 

How to include scripts located inside the node_modules folder?

I would use the path npm module and then do something like this:

var path = require('path');
app.use('/scripts', express.static(path.join(__dirname, 'node_modules/bootstrap/dist')));

IMPORTANT: we use path.join to make paths joining using system agnostic way, i.e. on windows and unix we have different path separators (/ and )

converting date time to 24 hour format

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Date date = new Date();
    Date date2 = new Date("2014/08/06 15:59:48");

    String currentDate = dateFormat.format(date).toString();
    String anyDate = dateFormat.format(date2).toString();

    System.out.println(currentDate);
    System.out.println(anyDate);

How to set custom header in Volley Request

In Kotlin,

You have to override getHeaders() method like :

val volleyEnrollRequest = object : JsonObjectRequest(GET_POST_PARAM, TARGET_URL, PAYLOAD_BODY_IF_YOU_WISH,
            Response.Listener {
                // Success Part  
            },

            Response.ErrorListener {
                // Failure Part
            }
        ) {
            // Providing Request Headers

            override fun getHeaders(): Map<String, String> {
               // Create HashMap of your Headers as the example provided below

                val headers = HashMap<String, String>()
                headers["Content-Type"] = "application/json"
                headers["app_id"] = APP_ID
                headers["app_key"] = API_KEY

                return headers
            }
        }

CFNetwork SSLHandshake failed iOS 9

In your project .plist file in add this permission :

<key>NSAppTransportSecurity</key>
<dict>
    <!--Connect to anything (this is probably BAD)-->
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

Java/ JUnit - AssertTrue vs AssertFalse

The course contains a logical error:

    assertTrue("Book check in failed", ml.checkIn(b1));

    assertFalse("Book was aleready checked in", ml.checkIn(b1));

In the first assert we expect the checkIn to return True (because checkin is succesful). If this would fail we would print a message like "book check in failed. Now in the second assert we expect the checkIn to fail, because the book was checked in already in the first line. So we expect a checkIn to return a False. If for some reason checkin returns a True (which we don't expect) than the message should never be "Book was already checked in", because the checkin was succesful.

Paste in insert mode?

While in insert mode hit CTRL-R {register}

Examples:

  • CTRL-R * will insert in the contents of the clipboard
  • CTRL-R " (the unnamed register) inserts the last delete or yank.

To find this in vim's help type :h i_ctrl-r

Android ListView not refreshing after notifyDataSetChanged

You are assigning reloaded items to global variable items in onResume(), but this will not reflect in ItemAdapter class, because it has its own instance variable called 'items'.

For refreshing ListView, add a refresh() in ItemAdapter class which accepts list data i.e items

class ItemAdapter
{
    .....

    public void refresh(List<Item> items)
    {
        this.items = items;
        notifyDataSetChanged();
    } 
}

update onResume() with following code

@Override
public void onResume()
{
    super.onResume();
    items.clear();
    items = dbHelper.getItems(); //reload the items from database
    **adapter.refresh(items);**
}

check the null terminating character in char*

Your '/0' should be '\0' .. you got the slash reversed/leaning the wrong way. Your while should look like:

while (*(forward++)!='\0') 

though the != '\0' part of your expression is optional here since the loop will continue as long as it evaluates to non-zero (null is considered zero and will terminate the loop).

All "special" characters (i.e., escape sequences for non-printable characters) use a backward slash, such as tab '\t', or newline '\n', and the same for null '\0' so it's easy to remember.

How can I delete multiple lines in vi?

it is dxd, not ddx

if you want to delete 5 lines, cursor to the beginning of the first line to delete and d5d

Android 'Unable to add window -- token null is not for an application' exception

Try getParent() at the argument place of context like new AlertDialog.Builder(getParent()); Hope it will work, it worked for me.

How to create duplicate table with new name in SQL Server 2008

I have used this query it is created new table with existing data.

Query : select * into [newtablename] from [existingtable]

Here is the link Microsoft instructions. https://docs.microsoft.com/en-us/sql/relational-databases/tables/duplicate-tables?view=sql-server-2017

What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

This command loads class of Oracle jdbc driver to be available for DriverManager instance. After the class is loaded system can connect to Oracle using it. As an alternative you can use registerDriver method of DriverManager and pass it with instance of JDBC driver you need.

Python Accessing Nested JSON Data

I did not realize that the first nested element is actually an array. The correct way access to the post code key is as follows:

r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()

print j['state']
print j['places'][1]['post code']

Declare and assign multiple string variables at the same time

You can to do it this way:

string Camnr = "", Klantnr = "", ... // or String.Empty

Or you could declare them all first and then in the next line use your way.

Responsive iframe using Bootstrap

Working during August 2020

use this

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

use one aspect ratio

<div class="embed-responsive embed-responsive-4by3">
  <iframe class="embed-responsive-item" src="…"></iframe>
</div>

within iframe use options

 <iframe class="embed-responsive-item" src="..."
  frameborder="0"
    style="
      overflow: hidden;
      overflow-x: hidden;
      overflow-y: hidden;
      height: 100%;
      width: 100%;
      position: absolute;
      top: 0px;
      left: 0px;
      right: 0px;
      bottom: 0px;
    "
    height="100%"
    width="100%"
  ></iframe>

Is there a <meta> tag to turn off caching in all browsers?

Try using

    <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <META HTTP-EQUIV="Expires" CONTENT="-1">

Python List vs. Array - when to use?

For almost all cases the normal list is the right choice. The arrays module is more like a thin wrapper over C arrays, which give you kind of strongly typed containers (see docs), with access to more C-like types such as signed/unsigned short or double, which are not part of the built-in types. I'd say use the arrays module only if you really need it, in all other cases stick with lists.

Disable XML validation in Eclipse

The other answers may work for you, but they did not cover my case. I wanted some XML to be validated, and others not. This image shows how to exclude certain folders (or files) for XML validation.

Begin by right clicking the root of your Eclipse project. Select the last item: Properties...

enter image description here

(If your browser scales this image very small, right click and open in a new window or tab.)

  • Eclipse appears to be very sensitive if you click the **Browse File...* or **Browser Folder...* button. This dialog needs some work!
  • This was done using Eclipse 4.3 (Kepler).

Using Exit button to close a winform program

Remove the method, I suspect you might also need to remove it from your Form.Designer.

Otherwise: Application.Exit();

Should work.

That's why the designer is bad for you. :)

Getting the difference between two repositories

git diff master remotes/b

That's incorrect. remotes/b is a remote, but not a branch.

To get it to work, I had to do:

git diff master remotes/b/master

Change label text using JavaScript

Use .textContent instead.

I was struggling with changing the value of a label as well, until I tried this.

If this doesn't solve try inspecting the object to see what properties you can set by logging it to the console with console.dir as shown on this question: How can I log an HTML element as a JavaScript object?

Convert Go map to json

It actually tells you what's wrong, but you ignored it because you didn't check the error returned from json.Marshal.

json: unsupported type: map[int]main.Foo

JSON spec doesn't support anything except strings for object keys, while javascript won't be fussy about it, it's still illegal.

You have two options:

1 Use map[string]Foo and convert the index to string (using fmt.Sprint for example):

datas := make(map[string]Foo, N)

for i := 0; i < 10; i++ {
    datas[fmt.Sprint(i)] = Foo{Number: 1, Title: "test"}
}
j, err := json.Marshal(datas)
fmt.Println(string(j), err)

2 Simply just use a slice (javascript array):

datas2 := make([]Foo, N)
for i := 0; i < 10; i++ {
    datas2[i] = Foo{Number: 1, Title: "test"}
}
j, err = json.Marshal(datas2)
fmt.Println(string(j), err)

playground

adding multiple event listeners to one element

This mini javascript libary (1.3 KB) can do all these things

https://github.com/Norair1997/norjs/

nor.event(["#first"], ["touchstart", "click"], [doSomething, doSomething]);

What throws an IOException in Java?

Assume you were:

  1. Reading a network file and got disconnected.
  2. Reading a local file that was no longer available.
  3. Using some stream to read data and some other process closed the stream.
  4. Trying to read/write a file, but don't have permission.
  5. Trying to write to a file, but disk space was no longer available.

There are many more examples, but these are the most common, in my experience.

Global Git ignore

Before reconfiguring the global excludes file, you might want to check what it's currently configured to, using this command:

git config --get core.excludesfile

In my case, when I ran it I saw my global excludes file was configured to

~/.gitignore_global
and there were already a couple things listed there. So in the case of the given question, it might make sense to first check for an existing excludes file, and add the new file mask to it.

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

Perhaps it is indirect to gdb (because it's an IDE), but my recommendations would be KDevelop. Being quite spoiled with Visual Studio's debugger (professionally at work for many years), I've so far felt the most comfortable debugging in KDevelop (as hobby at home, because I could not afford Visual Studio for personal use - until Express Edition came out). It does "look something similar to" Visual Studio compared to other IDE's I've experimented with (including Eclipse CDT) when it comes to debugging step-through, step-in, etc (placing break points is a bit awkward because I don't like to use mouse too much when coding, but it's not difficult).

How to save all files from source code of a web site?

Try Winhttrack

...offline browser utility.

It allows you to download a World Wide Web site from the Internet to a local directory, building recursively all directories, getting HTML, images, and other files from the server to your computer. HTTrack arranges the original site's relative link-structure. Simply open a page of the "mirrored" website in your browser, and you can browse the site from link to link, as if you were viewing it online. HTTrack can also update an existing mirrored site, and resume interrupted downloads. HTTrack is fully configurable, and has an integrated help system.

WinHTTrack is the Windows 2000/XP/Vista/Seven release of HTTrack, and WebHTTrack the Linux/Unix/BSD release...

How do I calculate power-of in C#?

Math.Pow() returns double so nice would be to write like this:

double d = Math.Pow(100.00, 3.00);

What is a tracking branch?

The ProGit book has a very good explanation:

Tracking Branches

Checking out a local branch from a remote branch automatically creates what is called a tracking branch. Tracking branches are local branches that have a direct relationship to a remote branch. If you’re on a tracking branch and type git push, Git automatically knows which server and branch to push to. Also, running git pull while on one of these branches fetches all the remote references and then automatically merges in the corresponding remote branch.

When you clone a repository, it generally automatically creates a master branch that tracks origin/master. That’s why git push and git pull work out of the box with no other arguments. However, you can set up other tracking branches if you wish — ones that don’t track branches on origin and don’t track the master branch. The simple case is the example you just saw, running git checkout -b [branch] [remotename]/[branch]. If you have Git version 1.6.2 or later, you can also use the --track shorthand:

$ git checkout --track origin/serverfix
Branch serverfix set up to track remote branch refs/remotes/origin/serverfix.
Switched to a new branch "serverfix"

To set up a local branch with a different name than the remote branch, you can easily use the first version with a different local branch name:

$ git checkout -b sf origin/serverfix
Branch sf set up to track remote branch refs/remotes/origin/serverfix.
Switched to a new branch "sf"

Now, your local branch sf will automatically push to and pull from origin/serverfix.

BONUS: extra git status info

With a tracking branch, git status will tell you whether how far behind your tracking branch you are - useful to remind you that you haven't pushed your changes yet! It looks like this:

$ git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

or

$ git status
On branch dev
Your branch and 'origin/dev' have diverged,
and have 3 and 1 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)

Angular 2 change event on every keypress

Use ngModelChange by breaking up the [(x)] syntax into its two pieces, i.e., property databinding and event binding:

<input type="text" [ngModel]="mymodel" (ngModelChange)="valuechange($event)" />
{{mymodel}}
valuechange(newValue) {
  mymodel = newValue;
  console.log(newValue)
}

It works for the backspace key too.

GZIPInputStream reading line by line

GZIPInputStream gzip = new GZIPInputStream(new FileInputStream("F:/gawiki-20090614-stub-meta-history.xml.gz"));
BufferedReader br = new BufferedReader(new InputStreamReader(gzip));
br.readLine();

How to Add a Dotted Underline Beneath HTML Text

Without CSS, you basically are stuck with using an image tag. Basically make an image of the text and add the underline. That basically means your page is useless to a screen reader.

With CSS, it is simple.

HTML:

<u class="dotted">I like cheese</u>

CSS:

u.dotted{
  border-bottom: 1px dashed #999;
  text-decoration: none; 
}

Running Example

Example page

<!DOCTYPE HTML>
<html>
<head>
    <style>
        u.dotted{
          border-bottom: 1px dashed #999;
          text-decoration: none; 
        }
    </style>
</head>
<body>
    <u class="dotted">I like cheese</u>
</body>
</html>

Text-decoration: none not working

Add a specific class for all the links :

html :

<a class="class1 class2 noDecoration"> text </a>

in css :

.noDecoration {
  text-decoration: none;
}

How to detect the OS from a Bash script?

This should be safe to use on all distros.

$ cat /etc/*release

This produces something like this.

     DISTRIB_ID=LinuxMint
     DISTRIB_RELEASE=17
     DISTRIB_CODENAME=qiana
     DISTRIB_DESCRIPTION="Linux Mint 17 Qiana"
     NAME="Ubuntu"
     VERSION="14.04.1 LTS, Trusty Tahr"
     ID=ubuntu
     ID_LIKE=debian
     PRETTY_NAME="Ubuntu 14.04.1 LTS"
     VERSION_ID="14.04"
     HOME_URL="http://www.ubuntu.com/"
     SUPPORT_URL="http://help.ubuntu.com/"
     BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"

Extract/assign to variables as you wish

Note: On some setups. This may also give you some errors that you can ignore.

     cat: /etc/upstream-release: Is a directory

Iterating over a numpy array

see nditer

import numpy as np
Y = np.array([3,4,5,6])
for y in np.nditer(Y, op_flags=['readwrite']):
    y += 3

Y == np.array([6, 7, 8, 9])

y = 3 would not work, use y *= 0 and y += 3 instead.

Please explain about insertable=false and updatable=false in reference to the JPA @Column annotation

According to Javax's persistence documentation:

Whether the column is included in SQL UPDATE statements generated by the persistence provider.

It would be best to understand from the official documentation here.

HTML form action and onsubmit issues

Try

onsubmit="return checkRegistration()"

jQuery posting JSON

You post JSON like this

$.ajax(url, {
    data : JSON.stringify(myJSObject),
    contentType : 'application/json',
    type : 'POST',
    ...

if you pass an object as settings.data jQuery will convert it to query parameters and by default send with the data type application/x-www-form-urlencoded; charset=UTF-8, probably not what you want

Spring MVC Missing URI template variable

This error may happen when mapping variables you defined in REST definition do not match with @PathVariable names.

Example: Suppose you defined in the REST definition

@GetMapping(value = "/{appId}", produces = "application/json", consumes = "application/json")

Then during the definition of the function, it should be

public ResponseEntity<List> getData(@PathVariable String appId)

This error may occur when you use any other variable other than defined in the REST controller definition with @PathVariable. Like, the below code will raise the error as ID is different than appId variable name:

public ResponseEntity<List> getData(@PathVariable String ID)

Using Excel as front end to Access database (with VBA)

Just skip the excel part - the excel user forms are just a poor man's version of the way more robust Access forms. Also Access VBA is identical to Excel VBA - you just have to learn Access' object model. With a simple application you won't need to write much VBA anyways because in Access you can wire things together quite easily.

jQuery, get html of a whole element

You can achieve that with just one line code that simplify that:

$('#divs').get(0).outerHTML;

As simple as that.

The server committed a protocol violation. Section=ResponseStatusLine ERROR

The culprit in my case was returning a No Content response but defining a response body at the same time. May this answer remind me and maybe others not to return a NoContent response with a body ever again.

This behavior is consistent with 10.2.5 204 No Content of the HTTP specification which says:

The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.

PHP send mail to multiple email addresses

Fore readability sake in the code use an array and implode it to a comma separated string:-

$recipients = array(
  "[email protected]",
  // more emails
);
$email_to = implode(',', $recipients); // your email address
$email_subject = "Contact Form Message"; // email subject line
$thankyou = "thankyou.htm"; // thank you page

Error: "Input is not proper UTF-8, indicate encoding !" using PHP's simplexml_load_string

Your 0xED 0x6E 0x2C 0x20 bytes correspond to "ín, " in ISO-8859-1, so it looks like your content is in ISO-8859-1, not UTF-8. Tell your data provider about it and ask them to fix it, because if it doesn't work for you it probably doesn't work for other people either.

Now there are a few ways to work it around, which you should only use if you cannot load the XML normally. One of them would be to use utf8_encode(). The downside is that if that XML contains both valid UTF-8 and some ISO-8859-1 then the result will contain mojibake. Or you can try to convert the string from UTF-8 to UTF-8 using iconv() or mbstring, and hope they'll fix it for you. (they won't, but you can at least ignore the invalid characters so you can load your XML)

Or you can take the long, long road and validate/fix the sequences by yourself. That will take you a while depending on how familiar you are with UTF-8. Perhaps there are libraries out there that would do that, although I don't know any.

Either way, notify your data provider that they're sending invalid data so that they can fix it.


Here's a partial fix. It will definitely not fix everything, but will fix some of it. Hopefully enough for you to get by until your provider fix their stuff.

function fix_latin1_mangled_with_utf8_maybe_hopefully_most_of_the_time($str)
{
    return preg_replace_callback('#[\\xA1-\\xFF](?![\\x80-\\xBF]{2,})#', 'utf8_encode_callback', $str);
}

function utf8_encode_callback($m)
{
    return utf8_encode($m[0]);
}

How do I auto-submit an upload form when a file is selected?

<form action="http://example.com">
    <input type="file" onchange="Submit()" />
</form>

 <script>
     // it will submit form 0 or you have to select particular form
     document.getElementsByTagName("form")[0].submit();       
 </script>

Getting current directory in VBScript

Your problem is not getting the directory (fso.GetAbsolutePathName(".") resolves the current working directory just fine). Even if you wanted the script directory instead of the current working directory, you could easily determine that as Jakob Sternberg described in his answer.

What does not work in your code is building a path from the directory and your executable. This is invalid syntax:

Directory = CurrentDirectory\attribute.exe

If you want to build a path from a variable and a file name, the file name must be specified as a string (or a variable containing a string) and either concatenated with the variable directory variable:

Directory = CurrentDirectory & "\attribute.exe"

or (better) you construct the path using the BuildPath method:

Directory = fso.BuildPath(CurrentDirectory, "attribute.exe")

How to know whether refresh button or browser back button is clicked in Firefox

For Back Button in jquery // http://code.jquery.com/jquery-latest.js

 jQuery(window).bind("unload", function() { //

and in html5 there is an event The event is called 'popstate'

window.onpopstate = function(event) {
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};

and for refresh please check Check if page gets reloaded or refreshed in Javascript

In Mozilla Client-x and client-y is inside document area https://developer.mozilla.org/en-US/docs/Web/API/event.clientX

What is inf and nan?

I use inf/-inf as initial values to find minimum/maximum value of a measurement. Lets say that you measure temperature with a sensor and you want to keep track of minimum/maximum temperature. The sensor might provide a valid temperature or might be broken. Pseudocode:

# initial value of the temperature
t = float('nan')          
# initial value of minimum temperature, so any measured temp. will be smaller
t_min = float('inf')      
# initial value of maximum temperature, so any measured temp. will be bigger
t_max = float('-inf')     
while True:
    # measure temperature, if sensor is broken t is not changed
    t = measure()     
    # find new minimum temperature
    t_min = min(t_min, t) 
    # find new maximum temperature
    t_max = max(t_max, t) 

The above code works because inf/-inf/nan are valid for min/max operation, so there is no need to deal with exceptions.

Resize image proportionally with MaxHeight and MaxWidth constraints

Much longer solution, but accounts for the following scenarios:

  1. Is the image smaller than the bounding box?
  2. Is the Image and the Bounding Box square?
  3. Is the Image square and the bounding box isn't
  4. Is the image wider and taller than the bounding box
  5. Is the image wider than the bounding box
  6. Is the image taller than the bounding box

    private Image ResizePhoto(FileInfo sourceImage, int desiredWidth, int desiredHeight)
    {
        //throw error if bouning box is to small
        if (desiredWidth < 4 || desiredHeight < 4)
            throw new InvalidOperationException("Bounding Box of Resize Photo must be larger than 4X4 pixels.");            
        var original = Bitmap.FromFile(sourceImage.FullName);
    
        //store image widths in variable for easier use
        var oW = (decimal)original.Width;
        var oH = (decimal)original.Height;
        var dW = (decimal)desiredWidth;
        var dH = (decimal)desiredHeight;
    
        //check if image already fits
        if (oW < dW && oH < dH)
            return original; //image fits in bounding box, keep size (center with css) If we made it bigger it would stretch the image resulting in loss of quality.
    
        //check for double squares
        if (oW == oH && dW == dH)
        {
            //image and bounding box are square, no need to calculate aspects, just downsize it with the bounding box
            Bitmap square = new Bitmap(original, (int)dW, (int)dH);
            original.Dispose();
            return square;
        }
    
        //check original image is square
        if (oW == oH)
        {
            //image is square, bounding box isn't.  Get smallest side of bounding box and resize to a square of that center the image vertically and horizontally with Css there will be space on one side.
            int smallSide = (int)Math.Min(dW, dH);
            Bitmap square = new Bitmap(original, smallSide, smallSide);
            original.Dispose();
            return square;
        }
    
        //not dealing with squares, figure out resizing within aspect ratios            
        if (oW > dW && oH > dH) //image is wider and taller than bounding box
        {
            var r = Math.Min(dW, dH) / Math.Min(oW, oH); //two dimensions so figure out which bounding box dimension is the smallest and which original image dimension is the smallest, already know original image is larger than bounding box
            var nH = oH * r; //will downscale the original image by an aspect ratio to fit in the bounding box at the maximum size within aspect ratio.
            var nW = oW * r;
            var resized = new Bitmap(original, (int)nW, (int)nH);
            original.Dispose();
            return resized;
        }
        else
        {
            if (oW > dW) //image is wider than bounding box
            {
                var r = dW / oW; //one dimension (width) so calculate the aspect ratio between the bounding box width and original image width
                var nW = oW * r; //downscale image by r to fit in the bounding box...
                var nH = oH * r;
                var resized = new Bitmap(original, (int)nW, (int)nH);
                original.Dispose();
                return resized;
            }
            else
            {
                //original image is taller than bounding box
                var r = dH / oH;
                var nH = oH * r;
                var nW = oW * r;
                var resized = new Bitmap(original, (int)nW, (int)nH);
                original.Dispose();
                return resized;
            }
        }
    }
    

PHP Parse error: syntax error, unexpected '?' in helpers.php 233

If you have newly upgraded your php version you might be forget to restart your webserver service.

How to implement the factory method pattern in C++ correctly

I mostly agree with the accepted answer, but there is a C++11 option that has not been covered in existing answers:

  • Return factory method results by value, and
  • Provide a cheap move constructor.

Example:

struct sandwich {
  // Factory methods.
  static sandwich ham();
  static sandwich spam();
  // Move constructor.
  sandwich(sandwich &&);
  // etc.
};

Then you can construct objects on the stack:

sandwich mine{sandwich::ham()};

As subobjects of other things:

auto lunch = std::make_pair(sandwich::spam(), apple{});

Or dynamically allocated:

auto ptr = std::make_shared<sandwich>(sandwich::ham());

When might I use this?

If, on a public constructor, it is not possible to give meaningful initialisers for all class members without some preliminary calculation, then I might convert that constructor to a static method. The static method performs the preliminary calculations, then returns a value result via a private constructor which just does a member-wise initialisation.

I say 'might' because it depends on which approach gives the clearest code without being unnecessarily inefficient.

Reporting Services export to Excel with Multiple Worksheets

Here are screenshots for SQL Server 2008 R2, using SSRS Report Designer in Visual Studio 2010.

I have done screenshots as some of the dialogs are not easy to find.

1: Add the group

SsrsAddGroup

2: Specify the field you want to group on

SsrsAddGroupDialog

3: Now click on the group in the 'Row Groups' selector, directly below the report designer

SsrsRowGroupsSelector

4: F4 to select property pane; expand 'Group' and set Group > PageBreak > BreakLocation = 'Between', then enter the expression you want for Group > PageName

SsrsGroupProperty

5: Here is an example expression

SsrsGroupPropertyDialog

Here is the result of the report exported to Excel, with tabs named according to the PageName expression

SsrsExcelTabs

Enable VT-x in your BIOS security settings (refer to documentation for your computer)

Check "Virtualization" status under performance option in your task manager. If you already have enabled it in your BIOS and still status is "Disabled", then go to bios, disable it and save & exit. Restart or shut down again. Enable it in BIOS again and save & exit. This time you'll see the status changed to "Enabled", It took me 3 attempts (don't know why it took that much time, but finally it worked).

What is a NullPointerException, and how do I fix it?

It's like you are trying to access an object which is null. Consider below example:

TypeA objA;

At this time you have just declared this object but not initialized or instantiated. And whenever you try to access any property or method in it, it will throw NullPointerException which makes sense.

See this below example as well:

String a = null;
System.out.println(a.toString()); // NullPointerException will be thrown

gnuplot : plotting data from multiple input files in a single graph

replot

This is another way to get multiple plots at once:

plot file1.data
replot file2.data

How to get the previous page URL using JavaScript?

You want in page A to know the URL of page B?

Or to know in page B the URL of page A?

In Page B: document.referrer if set. As already shown here: How to get the previous URL in JavaScript?

In page A you would need to read a cookie or local/sessionStorage you set in page B, assuming the same domains

Bytes of a string in Java

According to How to convert Strings to and from UTF8 byte arrays in Java:

String s = "some text here";
byte[] b = s.getBytes("UTF-8");
System.out.println(b.length);

How do I execute a file in Cygwin?

just type ./a in the shell

Optional args in MATLAB functions

There are a few different options on how to do this. The most basic is to use varargin, and then use nargin, size etc. to determine whether the optional arguments have been passed to the function.

% Function that takes two arguments, X & Y, followed by a variable 
% number of additional arguments
function varlist(X,Y,varargin)
   fprintf('Total number of inputs = %d\n',nargin);

   nVarargs = length(varargin);
   fprintf('Inputs in varargin(%d):\n',nVarargs)
   for k = 1:nVarargs
      fprintf('   %d\n', varargin{k})
   end

A little more elegant looking solution is to use the inputParser class to define all the arguments expected by your function, both required and optional. inputParser also lets you perform type checking on all arguments.

Error when trying vagrant up

If you're using OS X and used the standard install, Delete vagrant's old curl and it should now work

sudo rm /opt/vagrant/embedded/bin/curl

ArrayList insertion and retrieval order

Yes it remains the same. but why not easily test it? Make an ArrayList, fill it and then retrieve the elements!

jQuery - find child with a specific class

Based on your comment, moddify this:

$( '.bgHeaderH2' ).html (); // will return whatever is inside the DIV

to:

$( '.bgHeaderH2', $( this ) ).html (); // will return whatever is inside the DIV

More about selectors: https://api.jquery.com/category/selectors/

correct quoting for cmd.exe for multiple arguments

Spaces are horrible in filenames or directory names.

The correct syntax for this is to include every directory name that includes spaces, in double quotes

cmd /c C:\"Program Files"\"Microsoft Visual Studio 9.0"\Common7\IDE\devenv.com mysolution.sln /build "release|win32"

Variable not accessible when initialized outside function

Declare systemStatus in an outer scope and assign it in an onload handler.

systemStatus = null;

function onloadHandler(evt) {
    systemStatus = document.getElementById("....");
}

Or if you don't want the onload handler, put your script tag at the bottom of your HTML.

Reading a registry key in C#

You can use the following to get where the registry thinks it's installed:

(string)Registry.LocalMachine.GetValue(@"SOFTWARE\MyApplication\AppPath",
   "Installed", null);

Or you can use the following to find out where the application is actually being launched from:

System.Windows.Forms.Application.StartupPath

The latter is more reliable than the former if you're trying to use the .exe location as a relative path to find related files. The user could easily move things around after the install and still have the app work fine because .NET apps aren't so dependent upon the registry.

Using StartupPath, you could even do something clever like have your app update the registry entries at run time instead of crashing miserably due to missing/wrong/corrupted entries.

And be sure to look at the app settings functionality as storage for values rather than the registry (Properties.Settings.Default.mySettingEtc). You can read/write settings for the app and/or the user levels that get saved as simple MyApp.exe.config files in standard locations. A nice blast from the past (good old Win 3.1/DOS days) to have the application install/delete be a simple copy/delete of a folder structure or two rather than some convoluted, arcane install/uninstall routine that leaves all kinds of garbage in the registry and sprinkled all over the hard drive.

Cannot start MongoDB as a service

For mongoDB 3.0, You will have to set the following in the config file.

logpath=E:\mongoDBdata\log\mongoDB.log
dbpath=E:\mongoDBdata\db

the logpath should end with a file and not a folder.

Setting default values to null fields when mapping with Jackson

There is no annotation to set default value.
You can set default value only on java class level:

public class JavaObject 
{
    public String notNullMember;

    public String optionalMember = "Value";
}

Default value of 'boolean' and 'Boolean' in Java

The default value for a Boolean (object) is null.
The default value for a boolean (primitive) is false.

How to programmatically send SMS on the iPhone?

- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    UIImage *ui =resultimg.image;
    pasteboard.image = ui;
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms:"]];
}

javascript variable reference/alias

Whether you can alias something depends on the data type. Objects, arrays, and functions will be handled by reference and aliasing is possible. Other types are essentially atomic, and the variable stores the value rather than a reference to a value.

arguments.callee is a function, and therefore you can have a reference to it and modify that shared object.

function foo() {
  var self = arguments.callee;
  self.myStaticVar = self.myStaticVar || 0;
  self.myStaticVar++;
  return self.myStaticVar;
}

Note that if in the above code you were to say self = function() {return 42;}; then self would then refer to a different object than arguments.callee, which remains a reference to foo. When you have a compound object, the assignment operator replaces the reference, it does not change the referred object. With atomic values, a case like y++ is equivalent to y = y + 1, which is assigning a 'new' integer to the variable.

JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'

I had the same error on my Angular6 project. none of those solutions seemed to work out for me. turned out that the problem was due to an element which was specified as dropdown but it didn't have dropdown options in it. take a look at code below:

<span class="nav-link" id="navbarDropdownMenuLink" data-toggle="dropdown"
                          aria-haspopup="true" aria-expanded="false">
                        <i class="material-icons "
                           style="font-size: 2rem">notifications</i>
                        <span class="notification"></span>
                        <p>
                            <span class="d-lg-none d-md-block">Some Actions</span>
                        </p>
                    </span>
                    <div class="dropdown-menu dropdown-menu-left"
                         *ngIf="global.localStorageItem('isInSadHich')"
                         aria-labelledby="navbarDropdownMenuLink">
                                        <a class="dropdown-item" href="#">You have 5 new tasks</a>
                                        <a class="dropdown-item" href="#">You're now friend with Andrew</a>
                                        <a class="dropdown-item" href="#">Another Notification</a>
                                        <a class="dropdown-item" href="#">Another One</a>
                    </div>

removing the code data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" solved the problem.

I myself think that by each click on the first span element, the scope expected to set style for dropdown children which did not existed in the parent span, so it threw error.

Changing ImageView source

get ID of ImageView as

ImageView imgFp = (ImageView) findViewById(R.id.imgFp);

then Use

imgFp.setImageResource(R.drawable.fpscan);

to set source image programatically instead from XML.

How do I get the parent directory in Python?

Update from Python 3.4

Use the pathlib module.

from pathlib import Path
path = Path("/here/your/path/file.txt")
print(path.parent)

Old answer

Try this:

import os.path
print os.path.abspath(os.path.join(yourpath, os.pardir))

where yourpath is the path you want the parent for.

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

This is kind of a hack but the best solution that I have found is to use a description tag with no \item. This will produce an error from the latex compiler; however, the error does not prevent the pdf from being generated.

\begin{description} 
     <YOUR TEXT HERE> 
\end{description}
  • This only worked on windows latex compiler

How to clone object in C++ ? Or Is there another solution?

If your object is not polymorphic (and a stack implementation likely isn't), then as per other answers here, what you want is the copy constructor. Please note that there are differences between copy construction and assignment in C++; if you want both behaviors (and the default versions don't fit your needs), you'll have to implement both functions.

If your object is polymorphic, then slicing can be an issue and you might need to jump through some extra hoops to do proper copying. Sometimes people use as virtual method called clone() as a helper for polymorphic copying.

Finally, note that getting copying and assignment right, if you need to replace the default versions, is actually quite difficult. It is usually better to set up your objects (via RAII) in such a way that the default versions of copy/assign do what you want them to do. I highly recommend you look at Meyer's Effective C++, especially at items 10,11,12.

"Eliminate render-blocking CSS in above-the-fold content"

Consider using a package to automatically generate inline styles from your css files. A good one is Grunt Critical or Critical css for Laravel.

Authentication failed for https://xxx.visualstudio.com/DefaultCollection/_git/project

If you are entering your credentials into the Visual Studio popup you might see an error that says "Login was not successful". However, this might not be true. Studio will open a browser window saying that it was in fact successful. There is then a dance between the browser and Studio where you need to accept / allow the authentication at certain points.

Java Refuses to Start - Could not reserve enough space for object heap

You're using a 32-bit OS, so you're going to be seeing limits on the total size due to that. Other answers have covered this in more detail, so I'll avoid repeating their information.

A behaviour that I noticed with our servers recently is that specifying a maximum heap size with -Xmx while not specifying a minimum heap size with -Xms would lead to Java's server VM immediately attempting to allocate all of the memory needed for the maximum heap size. And sure, if the app gets up to that heap size, that's the amount of memory that you'll need. But the chances are, your apps will be starting out with comparitively small heaps and may require the larger heap at some later point. Additionally specifying the minimum heap size will let you start your app start with a smaller heap and gradually grow that heap.

All of this isn't going to help you increase your maximum heap size, but I figured it might help, so...

Calculate business days

Personally, I think this is a cleaner and more concise solution:

function onlyWorkDays( $d ) {
    $holidays = array('2013-12-25','2013-12-31','2014-01-01','2014-01-20','2014-02-17','2014-05-26','2014-07-04','2014-09-01','2014-10-13','2014-11-11','2014-11-27','2014-12-25','2014-12-31');
    while (in_array($d->format("Y-m-d"), $holidays)) { // HOLIDAYS
        $d->sub(new DateInterval("P1D"));
    }
    if ($d->format("w") == 6) { // SATURDAY
        $d->sub(new DateInterval("P1D"));
    }
    if ($d->format("w") == 0) { // SUNDAY
        $d->sub(new DateInterval("P2D"));
    }
    return $d;
}

Just send the proposed new date to this function.

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

According to this article on sqlserverstudymaterial;

Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).

If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.

If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

We faced the same problem:

ORA-29913: error in executing ODCIEXTTABLEOPEN callout
ORA-29400: data cartridge error error opening file /fs01/app/rms01/external/logs/SH_EXT_TAB_VGAG_DELIV_SCHED.log

In our case we had a RAC with 2 nodes. After giving write permission on the log directory, on both sides, everything worked fine.

Count the number of times a string appears within a string

This will fail though if the string can contain strings like "miscontrue".

   Regex.Matches("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "true").Count;

Iterate through object properties

Check this link it will help https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_state_forin

var person = {fname:"John", lname:"Doe", age:25}; 

  var text = "";
  var x;
  for (x in person) {
    text += person[x] + " "; // where x will be fname,lname,age
   }
Console.log(text);

how to run or install a *.jar file in windows?

The UnsupportedClassVersionError means that you are probably using (installed) an older version of Java as used to create the JAR.
Go to java.sun.com page, download and install a newer JRE (Java Runtime Environment).
if you want/need to develop with Java, you will need the JDK which includes the JRE.

Renaming files using node.js

For synchronous renaming use fs.renameSync

fs.renameSync('/path/to/Afghanistan.png', '/path/to/AF.png');

How to increase the max connections in postgres?

Adding to Winnie's great answer,

If anyone is not able to find the postgresql.conf file location in your setup, you can always ask the postgres itself.

SHOW config_file;

For me changing the max_connections alone made the trick.

Highlight a word with jQuery

Is it possible to get this above example:

jQuery.fn.highlight = function (str, className)
{
    var regex = new RegExp(str, "g");

    return this.each(function ()
    {
        this.innerHTML = this.innerHTML.replace(
            regex,
            "<span class=\"" + className + "\">" + str + "</span>"
        );
    });
};

not to replace text inside html-tags like , this otherwise breakes the page.

Python date string to date object

import datetime
datetime.datetime.strptime('24052010', '%d%m%Y').date()

Search code inside a Github project

While @VonC's answer works for some repositories, unfortunately for many repositories you can't right now. Github is simply not indexing them (as commented originally by @emddudley). They haven't stated this anywhere on their website, but they will tell you if you ask support:

From: Tim Pease
We have stopped adding newly pushed code into our codesearch index. The volume of code has outgrown our current search index, and we are working on moving to a more scalable search architecture. I'm sorry for the annoyance. We do not have an estimate for when this new search index will be up and running, but when it is ready a blog post will be published (https://github.com/blog).

Annoyingly there is no way to tell which repositories are not indexed other than the lack of results (which also could be from a bad query).

There also is no way to track this issue other than waiting for them to blog it (or watching here on SO).

From: Tim Pease
I am afraid our issue tracker is internal, but we can notify you as soon as the new search index is up and running.

what's the correct way to send a file from REST web service to client?

I don't recommend encoding binary data in base64 and wrapping it in JSON. It will just needlessly increase the size of the response and slow things down.

Simply serve your file data using GET and application/octect-streamusing one of the factory methods of javax.ws.rs.core.Response (part of the JAX-RS API, so you're not locked into Jersey):

@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFile() {
  File file = ... // Initialize this to the File path you want to serve.
  return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM)
      .header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"" ) //optional
      .build();
}

If you don't have an actual File object, but an InputStream, Response.ok(entity, mediaType) should be able to handle that as well.

How to check all versions of python installed on osx and centos

compgen -c python | grep -P '^python\d'

This lists some other python things too, But hey, You can identify all python versions among them.

Is it possible to specify condition in Count()?

@Guffa 's answer is excellent, just point out that maybe is cleaner with an IF statement

select count(IF(Position = 'Manager', 1, NULL)) as ManagerCount
from ...

How to get build time stamp from Jenkins build variables?

Build Timestamp Plugin will be the Best Answer to get the TIMESTAMPS in the Build process.

Follow the below Simple steps to get the "BUILD_TIMESTAMP" variable enabled.

STEP 1:

Manage Jenkins -> Plugin Manager -> Installed...
Search for "Build Timestamp Plugin".
Install with or without Restart.

STEP 2:

Manage Jenkins -> Configure System.
Search for 'Build Timestamp' section, then Enable the CHECKBOX.
Select the TIMEZONE, TIME format you want to setup with..Save the Page.

USAGE:

When Configuring the Build with ANT or MAVEN, 
Please declare a Global variable as, 
E.G.  btime=${BUILD_TIMESTAMP}
(use this in your Properties box in ANT or MAVEN Build Section)

use 'btime' in your Code to any String Variables etc..

enter image description here

enter image description here

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

It complains because it needs to use ssh instead of https but your git is still configured with https. so basically as others mentioned previously you need to either enable prompts or to configure git to use ssh instead of https. a simple way to do this by running the following:

git config --global --add url."[email protected]:".insteadOf "https://github.com/"

or if you already use ssh with git in your machine, you can safely edit ~/.gitconfig and add the following line at the very bottom

Note: This covers all SVC, source version control, that depends on what you exactly use, github, gitlab, bitbucket)

# Enforce SSH
[url "ssh://[email protected]/"]
  insteadOf = https://github.com/
[url "ssh://[email protected]/"]
        insteadOf = https://gitlab.com/
[url "ssh://[email protected]/"]
  insteadOf = https://bitbucket.org/
  • If you want to keep password pompts disabled, you need to cache password. For more information on how to cache your github password on mac, windows or linux, please visit this page.

  • For more information on how to add ssh to your github account, please visit this page.

Also, more importantly, if this is a private repository for a company or for your self, you may need to skip using proxy or checksum database for such repos to avoid exposing them publicly.

To do this, you need to set GOPRIVATE environment variable that controls which modules the go command considers to be private (not available publicly) and should therefore NOT use the proxy or checksum database.

The variable is a comma-separated list of patterns (same syntax of Go's path.Match) of module path prefixes. For example,

export GOPRIVATE=*.corp.example.com,github.com/mycompany/*

Or

go env -w GOPRIVATE=github.com/mycompany/*
  • For more information on how to solve private packages/modules checksum validation issues, please read this article.
  • For more information about go 13 modules and new enhancements, please check out Go 1.13 Modules Release notes.

One last thing not to forget to mention, you can still configure go get to authenticate and fetch over https, all you need to do is to add the following line to $HOME/.netrc

machine github.com login USERNAME password APIKEY
  • For GitHub accounts, the password can be a personal access tokens.
  • For more information on how to do this, please check Go FAQ page.

I hope this helps the community and saves others' time to solve described issues quickly. please feel free to leave a comment in case you want more support or help.

How do you get AngularJS to bind to the title attribute of an A tag?

It looks like ng-attr is a new directive in AngularJS 1.1.4 that you can possibly use in this case.

<!-- example -->
<a ng-attr-title="{{product.shortDesc}}"></a>

However, if you stay with 1.0.7, you can probably write a custom directive to mirror the effect.

MySQL Server has gone away when importing large sql file

If you are using MAMP on OS X, you will need to change the max_allowed_packet value in the template for MySQL.

  1. You can find it at: File > Edit template > MySQL my.cnf

  2. Then just search for max_allowed_packet, change the value and save.

Any way of using frames in HTML5?

I know your class is over, but in professional coding, let this be a lesson:

  • "Deprecated" means "avoid use; it's going to be removed in the future"
  • Deprecated things still work - just don't expect support or future-proofing
  • If the requirement requires it, and you can't negotiate it away, just use the deprecated construct.
    • If you're really concerned, develop the alternative implementation on the side and keep it ready for the inevitable failure
    • Charge for the extra work now. By requesting a deprecated feature, they are asking you to double the work. You're going to see it again anyway, so might as well front-load it.
    • When the failure happens, let the interested party know that this was what you feared; that you prepared for it, but it'll take some time
    • Deploy your solution as quickly as you can (there will be bugs)
    • Gain rep for preventing excessive downtime.

Convert NSData to String?

A simple way to convert arbitrary NSData to NSString is to base64 encode it.

NSString *base64EncodedKey = [keydata base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength];

You can then store it into your database for reuse later. Just decode it back to NSData.

Batch files: List all files in a directory with relative paths

You could simply get the character length of the current directory, and remove them from your absolute list

setlocal EnableDelayedExpansion
for /L %%n in (1 1 500) do if "!__cd__:~%%n,1!" neq "" set /a "len=%%n+1"
setlocal DisableDelayedExpansion
for /r . %%g in (*.log) do (
  set "absPath=%%g"
  setlocal EnableDelayedExpansion
  set "relPath=!absPath:~%len%!"
  echo(!relPath!
  endlocal
)

Changing password with Oracle SQL Developer

I realise that there are many answers, but I found a solution that may be helpful to some. I ran into the same problem, I am running oracle sql develop on my local computer and I have a bunch of users. I happen to remember the password for one of my users and I used it to reset the password of other users.

Steps:

  1. connect to a database using a valid user and password, in my case all my users expired except "system" and I remember that password

  2. find the "Other_users" node within the tree as the image below displays

enter image description here

3.within the "Other_users" tree find your users that you would like to reset password of and right click the note and select "Edit Users"

enter image description here

4.fill out the new password in edit user dialog and click "Apply". Make sure that you have unchecked "Password expired (user must change next login)".

enter image description here

And that worked for me, It is not as good as other solution because you need to be able to login to at least one account but it does work.

Why should text files end with a newline?

This originates from the very early days when simple terminals were used. The newline char was used to trigger a 'flush' of the transferred data.

Today, the newline char isn't required anymore. Sure, many apps still have problems if the newline isn't there, but I'd consider that a bug in those apps.

If however you have a text file format where you require the newline, you get simple data verification very cheap: if the file ends with a line that has no newline at the end, you know the file is broken. With only one extra byte for each line, you can detect broken files with high accuracy and almost no CPU time.

How to add an empty column to a dataframe?

@emunsing's answer is really cool for adding multiple columns, but I couldn't get it to work for me in python 2.7. Instead, I found this works:

mydf = mydf.reindex(columns = np.append( mydf.columns.values, ['newcol1','newcol2'])

How to filter empty or NULL names in a QuerySet?

this is another simple way to do it .

Name.objects.exclude(alias=None)

jQuery trigger file input

Based on Guillaume Bodi's answer I did this:

$('.fileinputbar-button').on('click', function() {
    $('article.project_files > header, article.upload').show();
    $('article.project_files > header, article.upload header').addClass('active');
    $('.file_content, article.upload .content').show();
    $('.fileinput-button input').focus().click();
    $('.fileinput-button').hide();
});

which means it's hidden to start with and then displayed for the trigger, then hidden again immediately.

Can't bind to 'ngForOf' since it isn't a known property of 'tr' (final release)

I was getting the same error, You can fix through one of this method:

  1. If you don't have any nested module

    a. Import the CommonModule in your App module

    b. Import your Component where you are adding the *ngFor in the App Module, define in declarations

// file App.modules.ts
@NgModule({
  declarations: [
    LoginComponent // declarations of your component
  ],
  imports: [
    BrowserModule
    DemoMaterialModule,
    FormsModule,
    HttpClientModule,
    ReactiveFormsModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })
  ],
  providers: [
    ApiService, 
    CookieService, 
    {
      provide: HTTP_INTERCEPTORS,
      useClass: ApiInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})

c. If you are using the separate module file for routing then Import the CommonModule in your Routing module else Import the CommonModule in your App module

// file app.routing.modules.ts
import { LoginComponent } from './login/login.component';
import { CommonModule } from "@angular/common";

const routes: Routes = [
  { path: '', component: LoginComponent },
  { path: 'login', component: LoginComponent }
];

@NgModule({
  imports: [RouterModule,RouterModule.forRoot(routes), CommonModule],
  exports: [RouterModule]
})
  1. If you have nested module then perform the 1st step in that particular module

In my case, the 2nd method solved my issue.
Hope this will help you

Django CSRF Cookie Not Set

I came across a similar situation while working with DRF, the solution was appending .as_view() method to the View in urls.py

Looking for a good Python Tree data structure

Would BTrees help? They're part of the Zope Object Database code. Downloading the whole ZODB package is a bit of overkill, but I hope the BTrees module would be at least somewhat separable.