Open specific Tab when link is clicked from another page

Question: Good day guys, I need help,
When a link is clicked on another page I need the tab to be displayed after the page loads, I've seen this being done using the hash #id but is there any possible way to do this with the data-filter as they're the ones controlling the tabs?

All

Tab1

Tab2

Tab3

Comment: for better answer what version of bootstrap do you use?
Comment: You can give css display:none; after that use jquery window on load event then make it display:initial; and you're done...
Comment: I'm using Bootstrap v3.3.0
Comment: You need to pass special request parameter from source page, for example `/my-page?tab=tab-name`. Then it is possible to use document [ready handler](http://learn.jquery.com/using-jquery-core/document-ready/) to get the parameter value and activate corresponding tab.
Comment: I'm not really skilled in Javascript @Alexander would you be able to help me out with the code on how to get this done?
Answer: You could pass special request parameter in query string. Then get the parameter value and activate corresponding tab.
For example, add tab-name into query string of target URL (the full relative URL is /my-page?tab-name=profile). Following expression returns value of the parameter, that equals to 'profile':
var tabName = (window.location.href.match(/[?&]tab-name=[^&$]+/i) || '=').split('=')[1];

If tab-name is omitted the expression returns empty string.
Then select navigation tab by received value and activate its associated pane using show method.

var tabName = (window.location.href.match(/[?&]tab-name=[^&$]+/i) || '=').split('=')[1];
tabName='profile'; // remove this line on real page
if(tabName.length)
  $('#myTabs .nav-link[href="#' + tabName + '"]').tab('show');
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    Home

    Profile

    Messages

    Settings

...

...

...

...

Note, in the snippet I set value of tabName directly, because it is not possible to send custom request to the snippet. So, you have to remove tabName='profile'; on your real page.
Comment: Hey thanks, this should work perfect for tabs that are setup to use id's to function instead of the data filter, think I should change my tab setup and use this method


Regex: Don't match if match is inside a URL

Question: I am trying to match all the hashtags in a description. However URLs sometimes appear in descriptions and URLs can sometimes contain the hashtag symbol.
Using regex, how can I avoid selecting hashtags if they are part of a URL?
Additionally, if a hashtag starts with a digit I want to ignore it because it is most likely not a hashtag but a list item.
Here is my current regex:
(https?:\/\/\S+)|#(.*?)[\s]

It mostly does not work, it erroneously matches #1, http://example.com/#urlpart and https://example.com#urlpart?s=search.
Comment: Ok, I see you are using it in JavaScript, you should have mentioned that from the start. Now, what are you doing? Extracting? Replacing (wrapping with some tags?)? Splitting?
Answer: JavaScript solution:
Match a URL and match and capture the hashtags that meet your requirements with
/https?:\/\/\S+|(#(?!\d)[^\s#]+)/ig

JS extraction demo:

const s = "regular text\n\n#1 0:33 - Cool thing <-- this should not match\n\nTag 2 and tag 3 should be treated as seperate hashtags\n#tag1 #tag2#tag3 \n\nHashtags inside URLs should be ignored\n\nhttp://example.com/#urlpart\n\nhttps://example.com#urlpart?s=search";
const regex = /https?:\/\/\S+|(#(?!\d)[^\s#]+)/ig;
const matches = [...s.matchAll(regex)];
console.log( Array.from(matches, x => x[1]).filter(Boolean) );

JS replacement demo:

const s = "regular text\n\n#1 0:33 - Cool thing <-- this should not match\n\nTag 2 and tag 3 should be treated as seperate hashtags\n#tag1 #tag2#tag3 \n\nHashtags inside URLs should be ignored\n\nhttp://example.com/#urlpart\n\nhttps://example.com#urlpart?s=search";
const regex = /https?:\/\/\S+|(#(?!\d)([^\s#]+))/ig;
console.log( s.replace(regex, (x,y,z) => y !== undefined ? `<a href="dir/${z}">${y}</a>` : `${x}` ) );

PCRE Solution
You may use
https?:\/\/\S+(*SKIP)(*F)|#(?!\d)[^\s#]+

See the regex demo
Details

https?:\/\/\S+(*SKIP)(*F) - match and skip URLs
| - or
#(?!\d)[^\s#]+ - match and return substrings matching

# - a # char
(?!\d)[^\s#]+ - any chunks of one or more chars other than # and whitespace not starting with a digit.
Comment: Trying to use `text.match(/https?:\/\/\S+(*SKIP)(*F)|#(?!\d)[^\s#]+/gm)` in javascript throws the error `VM2176:1 Uncaught SyntaxError: Invalid regular expression: Nothing to repeat`.
Comment: @Nostupidquestions That is JavaScript. My pattern is to be used with PCRE. I added a JavaScript solution.
Comment: @Nostupidquestions I added a linkifying JS code snippet to the answer.
Answer: You can turn the group around and capture what you want to keep. Then start the match with any char except a digit or whitespace char.
The value is in capture group 1.
\bhttps?:\/\/\S+|(#[^\s\d#][^\s#]*)

Explanation

\bhttps?:\/\/\S+ match the url
| Or
( Capture group 1

#[^\s\d#] Match # followed by any char except #, a digit or whitespace char
[^\s#]* Match 0+ times any char except # or a whitespace char

) Close group 1

Regex demo

const regex = /\bhttps?:\/\/\S+|(#[^\s\d#][^\s#]*)/gm;
const str = `regular text

#1 0:33 - Cool thing <-- this should not match

Tag 2 and tag 3 should be treated as seperate hashtags
#tag1 #tag2#tag3

Hashtags inside URLs should be ignored

http://example.com/#urlpart

https://example.com#urlpart?s=search`;

while ((m = regex.exec(str)) !== null) {
  if (m[1] !== undefined) console.log(m[1]);
}


PyTorch Datasets: Converting entire Dataset to NumPy

Question: I'm trying to convert the Torchvision MNIST train and test datasets into NumPy arrays but can't find documentation to actually perform the conversion.
My goal would be to take an entire dataset and convert it into a single NumPy array, preferably without iterating through the entire dataset.
I've looked at How do I turn a Pytorch Dataloader into a numpy array to display image data with matplotlib? but it doesn't address my issue.
So my question is, utilizing torch.utils.data.DataLoader, how would I go about converting the datasets (train/test) into two NumPy arrays such that all of the examples are present?
Note: I've left the batch size as the default of 1 for now; I could set it to 60,000 for train and 10,000 for test, but I'd prefer to not use magic numbers of that sort.
Thank you.
Answer: There is no need to use torch.utils.data.DataLoader for this task.
from torchvision import datasets, transforms

train_set = datasets.MNIST('./data', train=True, download=True)
test_set = datasets.MNIST('./data', train=False, download=True)

train_set_array = train_set.data.numpy()
test_set_array = test_set.data.numpy()

Note that in this case targets are excluded.
Comment: this does not include the transform though, where the accepted answer does.
Comment: This is because `data` and `targets` are not attributes of the `Dataset` class but of the `MNIST` class that subclasses from `Dataset`. I would direct to the documentation of `MNIST` of `torchvision` package but I don't think there is anything that answers the question asked here.
Comment: There is no practical reason to include labels in the same matrix of the
data. You can acquire another NumPy matrix of the targets running `train_set_array_targets = train_set.targets.numpy()`
Comment: that's very helpful, but does it give you the labels as well?
Comment: That is very much true. I was just missing the `data` and `targets` attributes of `Dataset` objects - which I could not seem to find in the documentation for some reason.
Answer: If I understand you correctly, you want to get the whole train dataset of MNIST images (in total 60000 images, each image of size 1x28x28 array with 1 for color channel) as a numpy array of size (60000, 1, 28, 28)?
from torchvision import datasets, transforms
from torch.utils.data import DataLoader

# Transform to normalized Tensors
transform = transforms.Compose([transforms.ToTensor(),
                                transforms.Normalize((0.1307,), (0.3081,))])

train_dataset = datasets.MNIST('./MNIST/', train=True, transform=transform, download=True)
# test_dataset = datasets.MNIST('./MNIST/', train=False, transform=transform, download=True)

train_loader = DataLoader(train_dataset, batch_size=len(train_dataset))
# test_loader = DataLoader(test_dataset, batch_size=len(test_dataset))

train_dataset_array = next(iter(train_loader))[0].numpy()
# test_dataset_array = next(iter(test_loader))[0].numpy()

This is the result:
>>> train_dataset_array

array([[[[-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         ...,
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296]]],

       [[[-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         ...,
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296]]],

       [[[-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         ...,
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296]]],

       ...,

       [[[-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         ...,
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296]]],

       [[[-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         ...,
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296]]],

       [[[-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         ...,
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296],
         [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296,
          -0.42421296, -0.42421296]]]], dtype=float32)

Edit: You can also get the labels by next(iter(train_loader))[1].numpy(). Alternatively you can use train_dataset.data.numpy() and train_dataset.targets.numpy(), but note that the data will not be transformed by transform as is done when using the dataloader.
Comment: I assume that I can use `next(iter(train_loader))[1].numpy()` to get the labels?
Comment: Yes, it gives the corresponding labels.


Angular 6 svg add class to path on click

Question: I am trying to add class into my svg map inside angular onclick event:
I have a working code it works inside ngOnInit() but when I add same code inside a click event function it is not working:
My  ngOnInit code is:
<code>   ngOnInit() {

      let a = document.getElementById("biharsvg")  as HTMLObjectElement;;

         a.addEventListener("load", function() {
              var svgDoc = a.contentDocument;
              var wchamparan = svgDoc.getElementById("wchamparan");

               console.log(wchamparan);

              wchamparan.onclick = function() {
               alert("hello");
                }
     })
}
</code>
This code is working fine I can see the log but when I am doing this in a click event on a button whose code is:
<code> click() {

 alert("hello");

 let a = document.getElementById("biharsvg")  as HTMLObjectElement;

 // var wchamparan = svgDoc.getElementById("wchamparan");
 // element.classList.add("mystyle");
    a.addEventListener("load", function() {
         let svgDoc = a.contentDocument;
         let wchamparan = svgDoc.getElementById("wchamparan");
         wchamparan.classList.add("mystyle");

         console.log("hello");
})
}
</code>
Here I can see the alert message I can also see what is inside a but a.addEventListener("load", function() I can't see anything. Why this is not working what is the difference between ngOnInit() and onclick function. What is wrong with this code.
Answer: I  tried many things to make it work when I remove addEventListener then it worked so my solution code is:
<code>appendToContainer() {
let map = document.getElementById("biharsvg") as HTMLObjectElement;
let svgDoc = map.contentDocument; // should be fine
let echamparan = svgDoc.getElementById("echamparan");
echamparan.classList.add("mystyle");
console.log(echamparan);
}
</code>
So the problem was I guess add event listener.


How do I keep track of a variable's value when it's passed into a function?

Question: Does JavaScript come with a way to keep track of a variable's identity when it's passed into a function?
For example:
var dog = 0;

function dogStuff(animal){
  animal = animal++;
}

In this example I would like to make dog == 1 by passing dog into the function:
dogStuff(dog);

such that
console.log(dog);

would print 1. People have marked this as duplicate to a couple of other questions, but those are a bit too complex for me, a beginner, to understand. I need some responses that assume I have little to no knowledge of JS.
Comment: You can't do that with primitives. What you *can* do is something like: `dog = dogStuff(dog);`
Comment: Also note that `==` is a boolean operation.
Comment: Use `window.dog++` inside `dogStuff()` function to get what you want
Comment: Possible duplicate of [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language)
Comment: Possible duplicate of [Javascript by reference vs. by value](https://stackoverflow.com/questions/6605640/javascript-by-reference-vs-by-value)
Answer: First things first: the line animal = animal++ won't do anything because it is a postfix increment. Either just do animal++ or ++animal to increment it.

Nope, dog will not be changed. JavaScript passes primitives by value (Thanks @ASDFGerte for the correction).
var dog = 0;
function dogStuff(animal) {
  animal++;
}
dogStuff(dog);
console.log(dog);  // prints 0

What you want to do (probably) is something similar to what @alfasin mentioned: return the updated value of dog.
var dog = 0;
function dogStuff(animal) {
  animal++;
  return animal;
}
dog = dogStuff(dog);
console.log(dog);  // prints 1

However, if you pass an object and reassign its properties, the original object will be modified (almost like pass by reference):
var dog = { age: 0 };
function incrementAge(animal) {
  animal.age++;
}
incrementAge(dog);
console.log(dog.age);  // prints 1

edit: If you want to assign multiple variables on return, one possible way to do it is to return an array of variables, which can then be assigned with deconstructed assignment:
var dog = 0;
var cat = 52;
function incrementTwoAnimals(animal1, animal2) {
  animal1++;
  animal2++;
  return [animal1, animal2];
}
[dog, cat] = incrementTwoAnimals(dog, cat);  // deconstructed assignment
console.log(dog, cat);  // prints 1, 53

Comment: Hmm what do you mean by "reassign its properties?"
Comment: @ASDFGerte Oops, I meant say pass by value. Fixed
Comment: Note that it's "primitives are passed by value", objects are a different story again, sometimes described as "pass by copy of reference"
Comment: @ JonathanLam Thanks! What if I need a function with multiple parameters and my program has multiple variables, like dogStuff(animal1, animal2) and variables dog, cat. If in a particular case the function only updates the value of one of the two variables, how do I tell the computer which variable to change with return. Like if dogStuff(cat,dog) only does animal1++ and not animal 2++, how do I get it to update cat with return?
Comment: @Christoph I'm glad this helped! I'll add an edit about ways to do multiple assignment with return
Answer: The function you posted did not return any value that you can use outside of it. So you need to add: return. This means that when you run dogStuff(...) it will actually return a value. And then you save that value in a variable, which can be the same dog that you passed as a parameter.
Here's the full code:
var dog = 0;

function dogStuff(animal){
   return animal++;
}

dog = dogStuff(dog);


How did the Bloody Girl die?

Question: Warning, this question is about some very end game content and contains spoilers!
How does the Bloody Girl die? The fire was set in the mansion, but as far as I understand, she was in the back house. Everybody else was in the mansion, and that's why they died.

 Except for Lucas, who jumps from the clocktower and survives. The Bloody girl is the pregnant wife of Lucas, that was awaiting for their baby in the back house.
Answer: It's deliberately ambiguous.
It's not made clear exactly how she died, only that she died before her child was born.
However, given that she's the only person whos death Lucas doesn't torment himself over, it's likely she died after the fire.

How did the Bloody Girl die?


I have build a todo list

Question: I have just build a todo list using html, CSS and JavaScript. So I have created a checkbox button so next it I want it when I click the button then strike out on the output.so how do I do that on JavaScript??
Comment: Hi, please provide your HTML, CSS and Javascript codes.
Comment: Welcome to stack overflow! Please take the [tour](https://stackoverflow.com/tour) to learn about the rules of the site as well as [how to ask](https://stackoverflow.com/help/how-to-ask) a good question.
Comment: pls provide your code
Comment: For the guy whoa sked for my code here it is:
Answer: There you go:

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

My To Do List

  <input type="text" id="myInput" placeholder="Title...">
  Add

Hit the gym

Pay bills

Meet George

Buy eggs

Read a book

Organize office

Source: W3Schools

I have build a todo list


Help - Prove using cases

Question: for every natural number n ≥ 1 the number $n^2 + n + 4$ is not a prime number
Hi there, I am trying to prove this using a proof by cases. I am just simply confused on how to do this or start this off.
Any help is appreciated.
Comment: Hint:  It's always even.
Comment: What Comes after $n\geq$?
Comment: Edit: Sorry, n ≥ 1
Answer: $$n^2+n+4=n(n+1)+4$$
$n(n+1)$ is always even, due to which the above expression is also even .
Also,
$$n^2+n+4\ge 1+1+4 = 6$$
Thus it can never be a prime number since the only even prime number is $2$

Help - Prove using cases


Why can you use open() as context manager?

Question: From Python's source code of open, I think open is just a normal function.
Why can  we use it like below?
with open('what_are_context_managers.txt', 'r') as infile:
    for line in infile:
        print('> {}'.format(line))

Since is neither implements __enter__ nor __exit__, nor uses contextlib.contextmanager decorator.
Comment: The original `file` type that is returned by the function implements the context manager interface.
Answer: You are not using the open function as a context manager. It is the result of the open(...) call expression that is the context manager. open() returns a file object, and it is that object that has __enter__ and __exit__ methods; see the io.IOBase documentation:

IOBase is also a context manager and therefore supports the with statement.

You can read the with statement like this:
_context_manager = open('what_are_context_managers.txt', 'r')
with _context_manager as infile:

Note that it is the return value of _context_manager.__enter__() that ends up being assigned to infile here. For file objects, file.__enter__() returns self, so you can get access to the same object that way.

As a side-note; you got the wrong open() function. The actual definition of the open() built-in is an alias for io.open(), see the _iomodule.c source code. The alias is set in initstdio() in pylifecycle.c (where io.OpenWrapper is itself an alias for _io.open). And yes, the documentation states the alias points the other way for end-user ease.


How to pass arrays into functions in C ( on Fedora )?

Question: Since I am a beginner have been practicing passing arrays as parameters to functions. Could someone explain why this program I wrote works fine on codeblox, but doesn't work in Fedora terminal (on Fedora it doesn't work for any number of scores). I'm using the GCC compiler.
#include<stdio.h>
int num,scores[]={},count,max,sum;
void input(int scores[]);
int findmax(int scores[]);
int findsum(int scores[]);
void display(int max,int sum);

int main()
{
    printf("Enter number of scores\n");
    scanf("%d",&num);

    input(scores);
    max=findmax(scores);
    sum=findsum(scores);
    display(max,sum);
    return 0;
}

void input(int scores[])
{
    for(count=0; count<num; count ++)
    {
    printf("Enter score #%d:\n",count);
    scanf("%d",&scores[count]);
    }

}

int findmax(int scores[])
{
    for(count=0; count<num ; count ++)
    {
        if(scores[count]>max)
    {
        max=scores[count];
        }

    }
    return max;
}

int findsum(int scores[])
{   sum=0;
    for(count=0; count<num ; count++ )
    {
    sum=sum+scores[count];
    }
    return sum;
}

void display(int max,int sum)
{
    printf("The max score is :%d\nThe total score is:%d\n",max,sum);
}

Comment: `scores[]={}` --> `scores[1024 /* Maximum number of assumed inputs*/];`
Comment: When passing an array into the function, you should also pass in the length of the array.
Comment: what do you mean by "doesn't work in fedora terminal".
 Show some I/O set
Comment: Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, **a specific problem or error** and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers.
Answer: You should avoid using global variables unless they are absolutely required. None are required here. All values should be declared local to main and should be passed to each function as a parameter, as required.
You must validate ALL input by, at minimum, checking the return of scanf (or whatever input function you are using). If a user simply pressed Enter (generating a '\n') or enters words instead of numbers causing the conversion to fail, you are dead in the water and may well be watching an infinite loop scroll by until you kill the process. (a cat might step on the keyboard, etc.)
When using the scanf family of functions, if a failure occurs, you must account for any characters left in the input buffer (e.g. stdin with scanf). If scanf is called within a loop, you risk an infinite loop where the conversion fails, leaving the same characters in the input buffer only to be read again, and fail, over-and-over again.
If you do not validate your input, you can have no confidence that you are processing a valid input from that point forward, and may in fact be well off into Undefined Behavior. The scanf family of functions returns the number of valid conversions based on the number of format-specifiers contained within the format-string. So with "%d", you have one format-specifier (e.g. %d), so upon successful conversion the return will be 1 (you should also check for EOF if the user manually cancels input with Ctrl + d, or Ctrl + z on windoze -- which is left to you)
Putting those pieces together, you could do something like the following:
#include <stdio.h>
#include <limits.h>     /* for INT_MIN */

#define MAX 512

void input (int *scores, int num);
int findmax (int *scores, int num);
int findsum (int *scores, int num);
void display (int max, int sum);

int main (void)
{
    int num, scores[MAX] = { 0 }, max, sum;

    printf ("Enter number of scores: ");
    if (scanf ("%d", &num) != 1) {  /* VALIDATE ALL input */
        fprintf (stderr, "error: invalid integer input.\n");
        return 1;
    }

    input (scores, num);
    max = findmax (scores, num);
    sum = findsum (scores, num);
    display (max, sum);

    return 0;
}

void input (int *scores, int num)
{
    int count = 0;

    while (count < MAX && count < num) {  /* always protect array bounds */
        printf ("Enter score [%d]: ", count);
        while (scanf ("%d", &scores[count]) != 1) { /* VALIDATE input */
            fprintf (stderr, "error: invalid input, try again.\n");
            /* remove invalid chars from input buffer */
            for (int c = getchar(); c != '\n' && c != EOF; c = getchar()) {}
            goto badval;
        }
        count++;
        badval:;
    }
}

int findmax (int *scores, int num)
{
    int max = INT_MIN, count;

    for (count = 0; count < num; count++)
        if (scores[count] > max)
            max = scores[count];

    return max;
}

int findsum (int *scores, int num)
{
    int sum = 0, count;

    for (count = 0; count < num; count++)
        sum = sum + scores[count];

    return sum;
}

void display (int max, int sum)
{
    printf ("\nThe max score is :%d\nThe total score is:%d\n", max, sum);
}

Example Use/Output
$ ./bin/maxminsum
Enter number of scores: 5
Enter score [0]: 9
Enter score [1]: 3
Enter score [2]: 7
Enter score [3]: 8
Enter score [4]: 2

The max score is :9
The total score is:29

With Error Correction
$ ./bin/maxminsum
Enter number of scores: 5
Enter score [0]: 9
Enter score [1]: 3
Enter score [2]: foo
error: invalid input, try again.
Enter score [2]: 7
Enter score [3]: 8
Enter score [4]: bar
error: invalid input, try again.
Enter score [4]: 2

The max score is :9
The total score is:29

Leave a comment if you have further questions.


Which is the correct Electrolux replacement element?

Question: I'm confused over a replacement part for my oven. It's an IKEA model manufactured by Electrolux. The PNC is 94406450601
According to Electrolux (and every third party spares site) the correct fan element for this oven is 3970123018 which is illustrated as a triple loop.

However, my old part is a double (not triple) loop and has the part number etched onto it as 397012801. Electrolux told me over the phone that this number is nothing to do with them and yet a product does exist by that number that looks identical to my faulty part. (double loop)

I note that the product number is suffixed with "7" giving 3970128017, but it seems too much of coincidence that the first 9 digits match and it looks the same.
Can anyone explain why the correct part looks completely wrong, but the other supposedly incompatible part looks like the correct one?
Answer: It is possible that a new element superseded the old. Electrolux is the parent to many brands, but from reading, Ikea, USA, ovens are rebranded Whirlpool. Try a whirpool part search. Either part should work, as long as the specs match, and the 3 turn fits in the hole. The part number listed on the part is the best choice for a direct replacement.
Comment: It's a 2kW/230V resistor, it will work, the problem is if it fits into the space in oven itself
Comment: Thanks. The only specs given are the same (2000W/230V) and also physical size. But suppliers refuse to say if whether the "wrong" one will work.
Comment: I would buy the part with the same part number as the one you have. Unless that part has failed quickly, it is possible it was the wrong one installed to begin with.


How to edit all the deployment of kubernetes at a time

Question: We have hundreds of deployment and in the config we have imagePullPolicy set as "ifnotpresent" for most of them and for few it is set to "always" now I want to modify all deployment which has ifnotpresent to always.
How can we achieve this with at a stroke?
Ex:
kubectl get deployment -n test -o json | jq '.spec.template.spec.contianer[0].imagePullPolicy="ifnotpresent"| kubectl -n test replace -f -

The above command helps to reset it for one particular deployment.
Comment: What sort of help are you looking for?  It sounds like you have the core of a script to do it already; the sort of mass update you describe isn't a typical Kubernetes operation and the CLI and API tools don't support it directly.
Answer: Kubernetes doesn't natively offer mass update capabilities. For that you'd have to use other CLI tools. That being said, for modifying existing resources, you can also use the kubectl patch function.
The script below isn't pretty, but will update all deployments in the namespace.
kubectl get deployments -o name | sed -e 's/.*\///g' | xargs -I {} kubectl patch deployment {} --type=json -p='[{"op": "replace", "path": "/spec/template/spec/containers/0/imagePullPolicy", "value": "Always"}]'

Note: I used sed to strip the resource type from the name as kubectl doesn't recognize operations performed on resources of type deployment.extensions (and probably others).
Comment: Thank you so much for this answer the "kubectl patch deployment" helped to do what i want.


T-SQL iteratively check history pattern

Question: How do you make a selection based on an item's prior history?
For example, I'm trying to select an item that has a val of 1, previously had a val of 10, and previously before that had a val of 1.  The only itemId that should satisfy the below data would be itemId = 3.
    WITH Items (itemId, date, val) AS (
      SELECT 1, CONVERT(datetime, '5/1/2011'), 6 UNION ALL
      SELECT 2, CONVERT(datetime, '5/1/2011'), 5 UNION ALL
      SELECT 3, CONVERT(datetime, '5/1/2011'), 1 UNION ALL
      SELECT 1, CONVERT(datetime, '6/1/2011'), 1 UNION ALL
      SELECT 2, CONVERT(datetime, '6/1/2011'), 10 UNION ALL
      SELECT 3, CONVERT(datetime, '6/1/2011'), 10 UNION ALL
      SELECT 1, CONVERT(datetime, '7/1/2011'), 1 UNION ALL
      SELECT 2, CONVERT(datetime, '7/1/2011'), 1 UNION ALL
      SELECT 3, CONVERT(datetime, '7/1/2011'), 1
    )
    select distinct itemId from Items where val = 1
    --and a previous date val = 10
    --and a previous previous date val = 1

Answer: This will get the specific answer you're after.  Not sure how useful it is in an abstract sense, though.  Are you always going to be looking for items that have exactly 3 values, 1-10-1?
SELECT
   A.itemID
FROM
   Items A
   INNER JOIN Items B ON A.itemID = B.itemID AND B.val = 10
   INNER JOIN Items C ON B.itemID = C.itemID AND C.val = 1
WHERE
   A.val = 1

Answer: Since you have the Value on Prior Date requirement, you have to use a ROW_NUM Ordering by the ItemId and the Date.
Then you do a two self joins on Id plus the RowNum joins to the one before it (in effect to the previous date), and add the WHERE clauses to 1-10-1
WITH Items_Original (itemId, date, val) AS
(
    SELECT 1, CONVERT(datetime, '5/1/2011'), 6 UNION ALL
    SELECT 2, CONVERT(datetime, '5/1/2011'), 5 UNION ALL
    SELECT 3, CONVERT(datetime, '5/1/2011'), 1 UNION ALL
    SELECT 1, CONVERT(datetime, '6/1/2011'), 1 UNION ALL
    SELECT 2, CONVERT(datetime, '6/1/2011'), 10 UNION ALL
    SELECT 3, CONVERT(datetime, '6/1/2011'), 10 UNION ALL
    SELECT 1, CONVERT(datetime, '7/1/2011'), 1 UNION ALL
    SELECT 2, CONVERT(datetime, '7/1/2011'), 1 UNION ALL
    SELECT 3, CONVERT(datetime, '7/1/2011'), 1
),
Items As
(
    Select
        ROW_NUMBER() OVER(ORDER BY ItemId, Date) AS RowNum, *
        FROM Items_Original
)
select *
from Items I1
    Inner JOIN Items I2
        On I1.itemId = I2.itemId
        And I1.RowNum = I2.RowNum-1
    Inner JOIN Items I3
        On I2.itemId = I3.itemId
        And I2.RowNum = I3.RowNum-1
Where 1=1
    And I1.val = 1
    And I2.val = 10
    And I3.val = 1

Answer:  WITH Items (itemId, date, val) AS (
      SELECT 1, CONVERT(datetime, '5/1/2011'), 6 UNION ALL
      SELECT 2, CONVERT(datetime, '5/1/2011'), 5 UNION ALL
      SELECT 3, CONVERT(datetime, '5/1/2011'), 1 UNION ALL
      SELECT 1, CONVERT(datetime, '6/1/2011'), 1 UNION ALL
      SELECT 2, CONVERT(datetime, '6/1/2011'), 10 UNION ALL
      SELECT 3, CONVERT(datetime, '6/1/2011'), 10 UNION ALL
      SELECT 1, CONVERT(datetime, '7/1/2011'), 1 UNION ALL
      SELECT 2, CONVERT(datetime, '7/1/2011'), 1 UNION ALL
      SELECT 3, CONVERT(datetime, '7/1/2011'), 1
    ),
cte as
(
    select *, row_number() over(partition by itemId order by date) [rn]
    from Items t
)

select distinct a.itemId
from cte a
join cte b on b.rn = a.rn + 1 and b.itemId = a.itemId
join cte c on c.rn = b.rn + 1 and c.itemId = a.itemId
where a.val = 1 and b.val = 10 and c.val = 1

T-SQL iteratively check history pattern


VBA Userform not populated when opened first time, but works the second time

Question: I'm working on Excel and making use of a userform. The idea is to highlight a row, then click a button which opens my useform. Column 10 of the active row consists of comments. I have coded the button so that when it is clicked, the textbox is automatically populated with the contents from column 10. The user can then add to these current comments and then press submit to make the changes.
The problem is that when the button is pressed the first time, the useform will not come populated with the comments. If I exit and do the procuedre again, then it works. What have I done wrong? The code for the button is below (textbox is called 'comment'):
Private Sub CommandButton1_Click()
    Dim ws1 As Worksheet

    Set ws1 = Worksheets("Now")
    UserForm1.Show
    'Add current comments to box
    UserForm1.Comment.Value = ws1.Cells(ActiveCell.row, 10).Value
End Sub

Comment: `ActiveCell` might be the culprit here. Why don't us use direct reference?
Comment: Note: Here at SO, you should not add "(Solved)"  to your title when your question is answered, but rather just Accept the correct answer (it's the big check mark) and the SO server will flag things appropriately.
Answer: Try rearranging your code to be like this:
Private Sub CommandButton1_Click()

Dim ws1 As Worksheet
Set ws1 = Worksheets("Now")
'Add current comments to box
UserForm1.comment.Value = ws1.Cells(ActiveCell.Row, 10).Value
UserForm1.Show
End Sub

This should load the data into the text box before it is shown to you.
Comment: Spot on! That makes sense as well. Ask it to do everything before and then show the form. Thank you for your effort. I will also edit the code to fix the typo


SQL Varchar Order

Question: Why when I have records like (ratings = varchar):
A - 100
B - 70
C - 30

Then:
SELECT * FROM `videos` ORDER BY `rating` DESC

Gives:
A - 30
B - 70
C - 100

And:
SELECT * FROM `videos` ORDER BY `rating` ASC

Gives:
A - 100
B - 70
C - 30

But when the (ratings = tinyint):
SELECT * FROM `videos` ORDER BY `rating` DESC

Gives:
A - 100
B - 70
C - 30

Comment: i cant see the difference between first and last query
Comment: i changed the rating column from varchar to tinyint, that fixed it. I want to know why.
Comment: aha sorry i didnt see it lmao.
Comment: your sample outputs don't make sense to me. Wouldn't A and B be reversed for your first two queries
Answer: When you have a varchar column, the length of the text data and the fact the char '0' comes before char '1' (rather than after char '9') affects the sort order.
e.g. compare
select '100' as col1
union all
select '70' as col1
order by col1 asc

with
select '100' as col1
union all
select '070' as col1
order by col1 asc

You can get around this by suitably padding all strings to the same length.
Comment: So as varchar with 3 rows 100, 76, 22. What would DESC be and why? I sorta got what your saying.
Answer: you can try:
SELECT * FROM videos ORDER BY rating, videos DESC

Comment: I already found the solution, I just want to know why when the column is varchar it don't work, and when its tinyint it works.

SQL Varchar Order


When Irelia uses Q, while dashing between her current location and the enemy's location, is she invulnerable to any spells, abilities or auto attacks?

Question: Today I was playing against Irelia and there was one moment when she seemed to be dodging my abilities using q.
Comment: You could add some more info for example: "What hero you using against Irelia and what Skill you use on Irelia."
Answer: No she is not invulnerable. It's a simple dash and nothing more. As you don't state which champion you played, its hard to tell why it seemed like that, but I'd guess, that she simply healed around the amount you dealt damage.


How to make program display an error message if the input doesn't start with a letter

Question: Just like what the title says i have been trying to do this for hours.
System.out.print ("Please input the first name: ");
name1 = in.next();

if (name1.substring(0,1).equals("[a-zA-Z]"))
System.out.println("\t" + name1.substring(0,1).toUpperCase()+name1.substring(1).toLowerCase() + "  is in the name list");

else if (name1.substring(0,1).equals("[0-9]"));
System.out.println("error");

This is part of the code that is not working out for me.
I dont really know where i went wrong im a beginner at this.
With this code whatever I write i get the second System.out.println back which is error. I want the program to display an error message if the string doesnt start with a number. Also, please use the if statement to do that because I couldn't use something I have not covered otherwise I would have searched it.
Comment: What do you think `equals("a-zA-Z")` does and why do you think so?
Comment: If trying to decide between `Character.isAlphabetic` versus `Character.isLetter`, check out the post about [the difference between them](http://stackoverflow.com/questions/18304804/what-is-the-difference-between-character-isalphabetic-and-character-isletter-in) for TL;DR, if it's always English, it doesn't matter :-)
Comment: @Tarik:  It's *slightly* stronger, but I'm not seeing it as a dupe to this one at all for reasons already elaborated on by Ascalonian.
Comment: Indeed. `equals` is not a regex match.
Comment: @SotiriosDelimanolis that is the last thing I used after using "contains" thinking it is the same as contains.
Comment: possible duplicate of [How to check if a string starts with one of several prefixes?](http://stackoverflow.com/questions/9790584/how-to-check-if-a-string-starts-with-one-of-several-prefixes)
Comment: @Tarik:  Going to have to disagree on that dupe there.  This is only checking a single letter after all; there are better ways to do it.
Comment: @Makoto in that case it's duplicate to that: http://stackoverflow.com/questions/8540015/determine-if-string-starts-with-letters-a-through-i
Comment: @Tarik - That's not a duplicate. They are looking for specific letters. The OP is asking for any letter
Comment: Yes you have absolutly right Mokoto and Ascalonian on that, and my apologizes to the OP, I can't see how to remove that flag
Answer: This should do it:
if(!Character.isAlphabetic(name1.charAt(0)) {
    //it's not a letter
}

Answer: I suggest you use Character.isLetter(char), name your variables and define them when you initialize them. Something like
Scanner in = new Scanner(System.in);
System.out.print ("Please input the first name: ");
String firstName = in.next();
if (Character.isLetter(firstName.charAt(0))) {
    // It is a letter.
} else {
    // It is not a letter.
}

Answer: Use matches if you want to use REGEX:
if (name1.substring(0,1).matches("[a-zA-Z]"))

equals checks for exact match. It will only be true if your first letter is "[a-zA-Z]" which will never happen.
Comment: Thankyou for the reply I also forgot to ask if it was possible to ignore the input if it did not start with a letter. I would appreciate it if you helped me in that.
Comment: @Abz Just saw your message. You can do anything you want to the input including "ignoring" it. But you still need to receive the input with a variable first, else there is no way to check whether the first letter is a letter.
Answer: The reason why you get the second print statement all the time is because you've added a ';' after the else if:
Change
else if (name1.substring(0,1).equals("[0-9]"));

To
else if (name1.substring(0,1).equals("[0-9]"))

Remove that semi colon first!
Comment: This is syntax suggestion, you could have added it in comments rather then an answer. This does not solve the problem even though.
Comment: True. But I think my answer does explain why he was getting "error" printed regardless of whatever he gave as an input, which is stated as part of the question.


Can't get the bootstrap navbar to show the toggle button when sizing to smaller resolution

Question: The navbar looks fine until resizing to a smaller resolution. When doing this, all the nav items disappear and the "hamburger icon" does not actually show up.

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#mydropdown">

    </button>

          Home

          Information

          Leaderboard

          Contact

Comment: Add  `navbar-light` to navbar
Answer: There is button in right side but you are not given color button. so white color. Add navbar-light to become more visible.
Your Demo with code - click right top side

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#mydropdown">

    </button>

          Home

          Information

          Leaderboard

          Contact

Solution Fixed

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#mydropdown">

    </button>

          Home

          Information

          Leaderboard

          Contact

Comment: I Hope this works perfectly. @Albert Vu , If any changes i would happy to change the answer too :). If the answer worked correclty don't forgot [to accept the answer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work).


Ubuntu 16.04: Chrome login expires after every roboot

Question: I am using HP Precision 3510 with Ubuntu 16.04.1 LTS (installed recently).
After installing I faced issues while installing chrome. I installed it using: sudo apt-get install -f then it installed the missing dependencies (got this idea from another questions). With this Chrome installed successfully but it comes with weird behavior.
After login into chrome browser to sync my bookmarks and other data, when I reboot my machine, chrome expires the login and ask me to login again.

Previously with Ubuntu 14.04 LTS this issue wasn't there. Any idea what is wrong here ?
Answer: Perhaps your Google account has 2-step verification enabled, and it's messing up with your app login? Is it the same when you're just restarting Chrome? Or does it happens only when you reboot?
Comment: It happens only when I am reooting
Comment: Do you have Google 2-step verification enabled with your account?
Comment: yes i have.. but chrome did asked me for verification code, i provided it as well. but still
Comment: In Ubuntu, I'm using Chromium not Google Chrome. Perhaps you could try to ask about your problem in here : https://productforums.google.com/forum/#!forum/chrome I think it is more apt for that forum.
Comment: May be you are right. Only thing I am not able to understand, Why Chrome behaving differently on my laptop but working just fine in my desktop (both of them running on Ubuntu 16.04)
Answer: Ah, finally I was able to find the issue. It was all because of keyring authentication. everytime I was starting Chrome, a keyring popup used to display and ask for password, but till then chrome has already initialized. After I reset the keyring password to blank, this issue got resolved. may be setting a blank password in keyring is not a good idea, but for time being it solved my problem.
Answer: Instead of resetting the keyring password to blank, you can also disable auto login when your Ubuntu starts in your system settings. I tested it on my machine and it resolved the issue.


Programmatically execute Ctrl-H

Question:
Possible Duplicate:
C# Simulate Key Press

I need a way in C# to "type" Ctrl+H in code when a user clicks a button.  I am working on a Word addin that customizes the ribbon.  When a user clicks my "Replace" button, I want the Replace dialog to show.  I can't figure out how to get to that dialog box, but Ctrl+H brings it up.  Is there a way to do that?
Comment: Keyboard shortcuts can be changed.
Answer: Take a look here at handling different key combinations. Are you using VSTO?
EDIT: Just reread and understand you're looking at typing those keys! I'll adjust accordingly!
EDIT: The question here covers simulating key presses.

Programmatically execute Ctrl-H


VS2010 - Structure change in CryptoAPI - v7.0A Vs v6.0A - WinCrypt.h

Question: In C:\Program Files\Microsoft SDKs\Windows\v7.0A\Include\WinCrypt.h, the definition for CERT_CHAIN_ENGINE_CONFIG is
typedef struct _CERT_CHAIN_ENGINE_CONFIG {

    DWORD       cbSize;
    HCERTSTORE  hRestrictedRoot;
    HCERTSTORE  hRestrictedTrust;
    HCERTSTORE  hRestrictedOther;
    DWORD       cAdditionalStore;
    HCERTSTORE* rghAdditionalStore;
    DWORD       dwFlags;
    DWORD       dwUrlRetrievalTimeout;      // milliseconds
    DWORD       MaximumCachedCertificates;
    DWORD       CycleDetectionModulus;

*#if (NTDDI_VERSION >= NTDDI_WIN7)
    HCERTSTORE  hExclusiveRoot;
    HCERTSTORE  hExclusiveTrustedPeople;
#endif*

} CERT_CHAIN_ENGINE_CONFIG, *PCERT_CHAIN_ENGINE_CONFIG;

I am using visual studio 2010 in an XP sp3 machine, in which case, i expect that the following  two members in the above structure gets greyed out. But this is not happening,
#if (NTDDI_VERSION >= NTDDI_WIN7)
    HCERTSTORE  hExclusiveRoot;
    HCERTSTORE  hExclusiveTrustedPeople;
#endif

NTDDI_VERSION in-turn is defined in sdkddkver.h as follows, and _WIN32_WINNT somehow takes the value of NTDDI_WIN7 which in my case is incorrect as mine is a XP SP3 machine.
#if !defined(_WIN32_WINNT) && !defined(_CHICAGO_)
#define  _WIN32_WINNT   0x0601
#endif
#ifndef NTDDI_VERSION
#ifdef _WIN32_WINNT
// set NTDDI_VERSION based on _WIN32_WINNT
#define NTDDI_VERSION   NTDDI_VERSION_FROM_WIN32_WINNT(_WIN32_WINNT)
#else
#define NTDDI_VERSION   0x06010000
#endif
#endif

The above two members of the structure CERT_CHAIN_ENGINE_CONFIG in question is not present in  C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\WinCrypt.hBut my 2010 visual studio project automatically pulls in the header and lib files from C:\Program Files\Microsoft SDKs\Windows\v7.0A\Include\WinCrypt.h Because of the conflicting structures, i am getting parameter is incorrect
Please advise how i can over come this issue?
Should i have to install visual studio 2010 sp1?
I found one reference in the web where it says initialising the structure will resolve the issue, but it will not, as the two parameters in question will not be greyed out and will be taken in while building.
UPDATE1:
Settings of my project:

$(VCInstalDir) - >C:\Program Files\Microsoft Visual Studio 10.0\VC
$(WindowsSdkDir) ->C:\Program Files\Microsoft SDKs\Windows\v7.0A
$(FrameworkSdkDir) ->C:\Program Files\Microsoft SDKs\Windows\v7.0A
Library file settings,
$(VCInstallDir)lib
$(VCInstallDir)atlmfc\lib
$(WindowsSdkDir)lib
$(FrameworkSDKDir)\lib

UPDATE 2:
My preprocessor definitions are
WIN32;_DEBUG;_WINDOWS;_USRDLL;MY_DLL_EXPORTS;%(PreprocessorDefinitions)

%(PreprocessorDefinitions) inherited values as follows
_WINDLL
_MBCS

Thanks
Answer:
the value of NTDDI_WIN7 which in my case is incorrect as mine is a XP SP3 machine.

As I understand it, the variables are initialized according to what system you are targeting, not what system you are compiling the code on. So you need to look at your project settings and see, what is your target platform, what headers are referenced etc. .
Comment: @Raj it's not about paths but about defines that your project has. Defines are specified on Compiler -> Preprocessor tab. Also some defines are set automatically when you choose different options. One idea: there's a page in the project properties dialog which lists all command line options. There you can see what defines are set.
Comment: @Eugene, My target systems will be XP,Vista,Win7, Server2003 and server 2008. Can you please elaborate your last sentence on how to configure the project settings. or some pointers to start with? Thanks
Comment: @Raj you have the project source code and I don't know where and how the defines are set in *your* project. If you search for "NTDDI_WIN7" in google, the very first link is http://msdn.microsoft.com/en-us/library/aa383745%28v=vs.85%29.aspx , which can be helpful to you (though it targets the opposite task to yours).
Comment: @Eugene. I have edited my original post with screen shots of my project settings. The link which you have shown is allowing me to define preprocessor directives that will restrict my target platforms rather than including them all. Is there anything you could recommend? Thanks
Comment: @Eugene. I couldn't get the preprocessor directives working, Instead i used the Platform Toolset and switched back to 6.0A and got it working without losing much other than the RSA_AES_XP provider name. I have added the preprocessor directive, if that gives any idea of how i can still rely on manipulating the preprocessor directives. thanks
Comment: You should be able to define version macro's once before the first include (eg in a precompiled header or something). Then you just change that if you change the OS you're targetting.
Answer: The problem which you have can be very easy explained. If you use v7.0A or v7.1 you are able to compile your project so that it will run under Windows 7. So the default value for the _WIN32_WINNT is 0x0601.
If you want co compile the program so that it will run on Windows XP you can define WINVER and _WIN32_WINNT explicitly. Typically one do this in the settings of the Visual Studio project inside of the preprocessor definitions. If you will do this the corresponding part of CERT_CHAIN_ENGINE_CONFIG structure will be displayed gray like you as want.
In the most cases and in the case of CERT_CHAIN_ENGINE_CONFIG it is not really needed. The Windows API are designed mostly so, that you will have no problems in the usage of CERT_CHAIN_ENGINE_CONFIG defined for Windows 7 in case of the start of the program on Windows XP. If you do define
#define WINVER 0x0500
#define _WIN32_WINNT 0x0500

(or 0x0501 instead of 0x0500) you will be able to run your program in the Windows 7, but you will be not able to use the hExclusiveRoot and the hExclusiveTrustedPeople members. The reason is the cbSize field which you should initialize as sizeof(CERT_CHAIN_ENGINE_CONFIG). It gives for the CertCreateCertificateChainEngine function enough information about the size of the input structure CERT_CHAIN_ENGINE_CONFIG. In case of small value of cbSize, the last HCERTSTORE members hExclusiveRoot and hExclusiveTrustedPeople will be just not used.


I use Lua script to copy mp4 files, but other apps(tiktok) cannot find the video

Question: Setelah salinan yang berjaya gagal, sistem video Android tidak dapat mengesan video copy.mp4,
dan juga tidak dapat mencari video copy.mp4 yang akan diterbitkan di TikTok.
<code> local ts = require("ts")
 path1 = "/sdcard/Download/aliyunPZ/1/copy.mp4"
 path2 = "/sdcard/Download/aliyunPZ/1/1.mp4"
 os.execute("cp " ..path1.. " "..path2)
</code>
1.mp4 can be detected by tiktok
copy.mp4 cannot be detected by tiktok
I don't know what is wrong?
I checked the permissions of two files (adb):
<code>-rw-rw---- root sdcard_rw 6939904 2020-11-13 20:21 1. mp4

-rw-rw---- root sdcard_rw 6939904 2020-11-14 1:54 copy. mp4
</code>
You can see the effect through the picture
Comment: [![tiktok (other applications) cannot detect copy.mp4][1]]
 [1]: https://i.stack.imgur.com/LscQ6.jpg
Comment: path = userPath().."/res/1.mp4"
os.execute("am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE -d file://"..path)
Answer: Hello sir change name your copy.mp4 to anything else


Old or new water damage on roof interior

Question: I've been in this (100-year old) house 3 years, and this area of the roof has always had marks of past water damage. I looked at it more closely today as we've been having a lot of melting and freezing lately (minnesota) and am not sure if it's getting worse.
Any tips on detecting if there is new water damage here? The wood feels cool to the touch, and hard to feel if it's damp vs just cool.
Answer: I don't see what looks like water damage. I see what looks like white-wash (old paint) on some of the roof 1x (one-by) components. It also looks like the white wash was put on the material before it was used to build the roof.
My guess is that the two 1x12s, with the white streaks, had the white-wash dripped on them, maybe while the other materials were being painted.
Another guess is that your pictures show some 100 year-old material re-purposing. Like a white-washed chicken coop was dismantled and the boards were used on the house.


AWS SDK for Java S3 bucket Access Key Id issue

Question: I am trying to access an Amazon S3 bucket programmatically through Java libraries. (to do basic cloud management from a third-party application). As a first step, I tried to print whether a bucket exists or not(3rd line)
AWSCredentials credentials=new BasicAWSCredentials("my-Access- Key","My- Secret-Key");
AmazonS3 s3client = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials)).withRegion(Regions.AP_EAST_1).build();
String bucketExists=String.valueOf(s3client.doesBucketExistV2("newBucketName"));

When I run this line of code, I am getting an exception saying that
com.amazonaws.services.s3.model.AmazonS3Exception: The AWS Access Key Id you provided does not exist in our records. (Service: Amazon S3; Status Code: 403; Error Code: InvalidAccessKeyId; Request ID:RequestId...)

I don't want to maintain a credentials file in the .aws folder for
the following reason:
I am trying to variablilize the access credentials
based on the logged-in user from a secure LDAP system, so I can
confirm the feasibility only when I test it with hard-coded
credentials.
I have checked that the issue is not one of the below

I have created an IAM user with a valid Access ID and Secret Key in
the AWS console and have enabled the user for programmatic access.
I have also given applied the AmazonS3FullAccess policy for IAM user
The key is in Active state(have checked it through the console)
I have added the dependency for the AWS SDK to gradle (implementation group: 'com.amazonaws', name: 'aws-java-sdk-s3', version: '1.12.15')

Please let me know what the issue might be. My apologies if it is an amateur issue.
Comment: Hi @Sachu. It is very strange. You can set the environment variables information where you consider appropriate. What IDE are you using? Maybe simpler, although I never tested it, you can try providing the necessary information using the java system properties aws.accessKeyId and aws.secretKey. Please, do not forget to change the credentials provider implementation accordingly. Also, although it should not be a problem, have you tried removing the region information? It should not be a problem in any way, but as I told you your code looks fine to me.
Comment: I am very happy to hear that the problem is solved @Sachu. Thank you very much, I posted an answer summarizing these comments. Please, do not hesitate to contact me again if you thing I can be of any help.
Comment: your code looks fine, there is not a reason why it should not work properly. Have you tried to create a new access key? Probably there is something wrong with that key. From time to time it happens. Please, can you try with a different access key? If you created another user, another thing you can try is to use an access key for that other user.
Comment: Thank you for the suggestion. I tried this but am facing the same error with the new set of credentials
Comment: Hi @Sachu. I see. It is very strange indeed. I am aware that you need to provide explictely the credentials but, just for testing, have you tried to use the same credentials as environment variables, for example? Did it work?
Comment: @jccampanero I tried adding the credentials to the credentials file in C:\Users\\.aws folder. It still did not work. I followed the pattern given in this https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html  . I am using Windows OS. I don't know where to put the code to the set AWS_ACCESS_KEY_ID=your_access_key_id
Comment: Hi @jccampanero I tried adding the system properties but still got the same Access key error. When I removed the region, I got a socket timed-out error. When I added it back i got the same access Key issue. I think I am missing some other key component or configuration. If I can change something to make it work I will accept your answer and award the bounty.
Comment: Thank you @Sachu. The important thing is that you can successfully access your resources. Is the bucket created in the same region your are using in your Java code? Please, from a totally different point of view, remove any credentials you may have in your home directory if possible, maybe you have something there and it is causing the issue.
Comment: Please, try as well providing the provider chain, it will remove any dependency with other possible credentials configuration: `AmazonS3 s3client = AmazonS3ClientBuilder.standard().withCredentials(new AWSCredentialsProviderChain(new AWSStaticCredentialsProvider(credentials))).withRegion(Regions.AP_EAST_1).build();`. Note the use of `AWSCredentialsProviderChain`
Comment: Thank you @jccampanero. I had to use the right region in the bucket and the console and remove the other credentials in the home directory. It worked. Please post this as an answer. I will accept and award bounty
Answer: As indicated in the question comments, your code looks fine and it should work properly.
The most likely reason of the problem is that AWS is picking up other credentials from somewhere else. Please, try removing other credentials like the ones stored in the home directory in order to be sure that the SDK is using the right credentials when contacting S3.
In addition, please, verify that you are providing the right region according to your S3 bucket as well.
Answer: You are using the older V1 API. The Service Client name for V1 is AmazonS3. Likewise, the V2 service client name is  S3Client. Amazon strongly recommends moving to V2:
The AWS SDK for Java 2.x is a major rewrite of the version 1.x code base. It's built on top of Java 8+ and adds several frequently requested features. These include support for non-blocking I/O and the ability to plug in a different HTTP implementation at run time.
Try following this step by step set of instructions, which is based on V2.
Get started with the AWS SDK for Java 2.x
WHen working with V2, you can put your creds in a file located in a .aws folder named credentials, as explained in this document. Once you follow all steps in this document, you can programmatically access an Amazon S3 bucket.
Comment: Thank you for your idea . But I don't want to use the credentials file since I wanted to variabilize the access credentials based on the LDAP user. I tried the same with V2 (S3 Client) but received the same error.


On Conflict Do Nothing in Postgres with a not-null constraint

Question: Is it not possible to utilize "ON CONFLICT DO NOTHING" to avoid inserting and violating a not-null constraint?
For example...
INSERT INTO public.users (user, user_yob, sex)
SELECT mom, mom_yob, 'F'
FROM staging.users
ON CONFLICT DO NOTHING;

Produces this error and stops...
INSERT INTO public.users (user, user_yob, sex) SELECT mom, mom_yob, 'F' FROM staging.users ON CONFLICT DO NOTHING
> ERROR:  null value in column "user" violates not-null constraint
  DETAIL:  Failing row contains (0b159b81-6842-4ae7-961c-2e9cff8488b1, null, null, null, null, null, null, null, null, null, F).

Ideally, this particular insert would be ignored rather than raise the error.
Comment: Related: https://dba.stackexchange.com/questions/292428/postgresql-upsert-issue-with-not-null-columns
Answer: As the documentation says:

The optional ON CONFLICT clause specifies an alternative action to raising a unique violation or exclusion constraint violation error.

NOT NULL is neither a unique nor an exclusion constraint. Technically speaking, it is not even a proper constraint in PostgreSQL.
What you need is a BEFORE INSERT trigger that returns NULL if the NEW row contains offending null values.
Comment: Thank you and that makes sense... I read the docs but didn't realize that "not-null" is not technically a constraint. Is there a better way to do this than just setting "NOT NULL" on a column?
Comment: No; what's wrong with `NOT NULL`? Did you investigate the option of using a trigger?
Comment: I just making sure I wasn't missing something else. I'm doing the trigger now and it does the trick. I'll accept your answer.


Skew CSS - Keep elements in top right and bottom left corners

Question: Hello i'm trying to find the best way of keeping my skewed elements in place whist resizing page.
I want to be able to extend the content area (green area) and keep that the same shape but also have the white corners the same shape as well.
Sorry for my lack of knowledge in this area, i'm currently still learning this
I will accept JavaScript or JQuery solutions.
Here is an example what I have so far:

/* Latest compiled and minified CSS included as External Resource*/

.container-fluid{
  background: green;
  padding: 0px;
  color: black;
  position: relative;
}
.container{
  padding: 50px;
}

.overlay-top-right {
    position: absolute;
    right: 0;
    top: 0;
    height: 300px;
    width: 30%;
    background: #ffffff;
    transform-origin: top right;
    -ms-transform: skew(45deg,0deg);
    -webkit-transform: skew(45deg,0deg);
    transform: skew(45deg,0deg);
}

.overlay-bottom-left {
    position: absolute;
    left: 0;
    bottom: 0;
    height: 300px;
    width: 40%;
    background: #ffffff;
    transform-origin: bottom left;
    -ms-transform: skew(45deg,0deg);
    -webkit-transform: skew(45deg,0deg);
    transform: skew(45deg,0deg);
}
/* Optional theme */
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis tempus arcu a nisl bibendum interdum sed in velit. Etiam semper sem ac nisl rhoncus, at molestie lectus laoreet. Phasellus pulvinar libero mi, a aliquet felis condimentum ut. Morbi massa libero, finibus vitae pellentesque vitae, dignissim sed purus. Ut volutpat consequat commodo. Praesent consequat eget mauris sed viverra. Etiam ac dui vel turpis rutrum tincidunt eu vitae orci. Nunc rhoncus molestie eros nec aliquet. Vestibulum et blandit orci, vitae molestie massa. Morbi hendrerit orci ac interdum tincidunt. Nulla facilisi. Nulla blandit purus eget mattis eleifend. Etiam blandit, enim vel porttitor mollis, diam massa suscipit metus, ut ornare tellus arcu nec orci.

Pellentesque bibendum dignissim tincidunt. Morbi vel sem lacus. Cras vitae laoreet eros. Aenean hendrerit ante semper, auctor ligula et, interdum sapien. Duis placerat urna at velit tincidunt commodo. Fusce condimentum mauris ut ornare euismod. Duis iaculis, augue in varius pretium, justo ligula volutpat est, et ornare dui nibh a sem. Quisque sit amet ultricies tortor.

Praesent egestas tincidunt massa convallis elementum. Fusce ac nisl sed arcu placerat commodo ut a lacus. Donec eget blandit lacus. Vivamus ac efficitur nunc. Nulla facilisi. Phasellus vel ipsum tempus, imperdiet dolor quis, rhoncus magna. Duis lobortis, nisl non lobortis faucibus, risus metus ullamcorper mauris, a ultricies quam nibh vitae sapien. Nulla facilisi. Donec luctus in libero vel pharetra. Maecenas mollis quam libero, eget pellentesque risus convallis at. Morbi laoreet vitae urna id accumsan. Etiam eu porttitor dolor. Curabitur eu sagittis augue. Phasellus at laoreet lacus. Donec interdum aliquet consectetur.

Etiam vestibulum sapien in metus iaculis bibendum. Fusce aliquet sodales leo, et interdum nisl gravida non. Quisque eget lobortis metus, ac euismod ipsum. Cras ac gravida purus. Integer erat orci, feugiat eget tortor sit amet, semper fringilla tortor. Duis luctus at magna sodales efficitur. Donec enim nulla, tempor vel dictum nec, porta vel dolor. Vivamus semper dui tortor. Curabitur turpis mi, mollis a sodales sodales, feugiat eu nisi. Pellentesque non fringilla nisl. Donec at dapibus libero, sed tempor arcu. Pellentesque velit ante, interdum in orci at, feugiat viverra orci. Quisque egestas a tortor et ullamcorper. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nullam ut nunc tempor, dictum orci eu, pharetra enim.

Sed accumsan sem ipsum. Integer id dolor quis massa tempor congue ac ut nisi. Pellentesque nulla lectus, efficitur non sagittis quis, ornare vel nisl. Proin tempor ullamcorper turpis, et hendrerit est fermentum rutrum. Ut ligula nisi, varius quis sodales at, euismod et diam. Mauris vel sem a mi eleifend fringilla. Suspendisse magna magna, lacinia sit amet nisl eu, laoreet ultricies erat. Suspendisse non orci ante. Aliquam interdum ac lacus eget ornare. Vestibulum dictum felis vitae hendrerit interdum. Duis quis tempus urna.
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis tempus arcu a nisl bibendum interdum sed in velit. Etiam semper sem ac nisl rhoncus, at molestie lectus laoreet. Phasellus pulvinar libero mi, a aliquet felis condimentum ut. Morbi massa libero, finibus vitae pellentesque vitae, dignissim sed purus. Ut volutpat consequat commodo. Praesent consequat eget mauris sed viverra. Etiam ac dui vel turpis rutrum tincidunt eu vitae orci. Nunc rhoncus molestie eros nec aliquet. Vestibulum et blandit orci, vitae molestie massa. Morbi hendrerit orci ac interdum tincidunt. Nulla facilisi. Nulla blandit purus eget mattis eleifend. Etiam blandit, enim vel porttitor mollis, diam massa suscipit metus, ut ornare tellus arcu nec orci.

Pellentesque bibendum dignissim tincidunt. Morbi vel sem lacus. Cras vitae laoreet eros. Aenean hendrerit ante semper, auctor ligula et, interdum sapien. Duis placerat urna at velit tincidunt commodo. Fusce condimentum mauris ut ornare euismod. Duis iaculis, augue in varius pretium, justo ligula volutpat est, et ornare dui nibh a sem. Quisque sit amet ultricies tortor.

Praesent egestas tincidunt massa convallis elementum. Fusce ac nisl sed arcu placerat commodo ut a lacus. Donec eget blandit lacus. Vivamus ac efficitur nunc. Nulla facilisi. Phasellus vel ipsum tempus, imperdiet dolor quis, rhoncus magna. Duis lobortis, nisl non lobortis faucibus, risus metus ullamcorper mauris, a ultricies quam nibh vitae sapien. Nulla facilisi. Donec luctus in libero vel pharetra. Maecenas mollis quam libero, eget pellentesque risus convallis at. Morbi laoreet vitae urna id accumsan. Etiam eu porttitor dolor. Curabitur eu sagittis augue. Phasellus at laoreet lacus. Donec interdum aliquet consectetur.

Etiam vestibulum sapien in metus iaculis bibendum. Fusce aliquet sodales leo, et interdum nisl gravida non. Quisque eget lobortis metus, ac euismod ipsum. Cras ac gravida purus. Integer erat orci, feugiat eget tortor sit amet, semper fringilla tortor. Duis luctus at magna sodales efficitur. Donec enim nulla, tempor vel dictum nec, porta vel dolor. Vivamus semper dui tortor. Curabitur turpis mi, mollis a sodales sodales, feugiat eu nisi. Pellentesque non fringilla nisl. Donec at dapibus libero, sed tempor arcu. Pellentesque velit ante, interdum in orci at, feugiat viverra orci. Quisque egestas a tortor et ullamcorper. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nullam ut nunc tempor, dictum orci eu, pharetra enim.

Sed accumsan sem ipsum. Integer id dolor quis massa tempor congue ac ut nisi. Pellentesque nulla lectus, efficitur non sagittis quis, ornare vel nisl. Proin tempor ullamcorper turpis, et hendrerit est fermentum rutrum. Ut ligula nisi, varius quis sodales at, euismod et diam. Mauris vel sem a mi eleifend fringilla. Suspendisse magna magna, lacinia sit amet nisl eu, laoreet ultricies erat. Suspendisse non orci ante. Aliquam interdum ac lacus eget ornare. Vestibulum dictum felis vitae hendrerit interdum. Duis quis tempus urna.

Answer: You may replace your elements by :before and :after on the text area and use floating like this:

/* Latest compiled and minified CSS included as External Resource*/

.container-fluid{
  background: green;
  padding: 0px;
  color: black;
  position: relative;
}
.container{
  padding: 50px;
  overflow:hidden;
}
.overlay {
position:relative;
}
.overlay:before {
    content:" ";
    float:right;
    margin-right: -50px;
    margin-top: -50px;
    height: 150px;
    width: 150px;
    background: #ffffff;
    transform-origin: top right;
    -ms-transform: skew(45deg,0deg);
    -webkit-transform: skew(45deg,0deg);
    transform: skew(45deg,0deg);
}

.overlay:after {
    content:" ";
    float:left;
    position:relative;
    margin-left: -50px;
    margin-bottom: -50px;
    height: 100px;
    width: 100px;
    background: #ffffff;
    transform-origin: bottom left;
    -ms-transform: skew(45deg,0deg);
    -webkit-transform: skew(45deg,0deg);
    transform: skew(45deg,0deg);
}
/* Optional theme */

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis tempus arcu a nisl bibendum interdum sed in velit. Etiam semper sem ac nisl rhoncus, at molestie lectus laoreet. Phasellus pulvinar libero mi, a aliquet felis condimentum ut. Morbi massa libero, finibus vitae pellentesque vitae, dignissim sed purus. Ut volutpat consequat commodo. Praesent consequat eget mauris sed viverra. Etiam ac dui vel turpis rutrum tincidunt eu vitae orci. Nunc rhoncus molestie eros nec aliquet. Vestibulum et blandit orci, vitae molestie massa. Morbi hendrerit orci ac interdum tincidunt. Nulla facilisi. Nulla blandit purus eget mattis eleifend. Etiam blandit, enim vel porttitor mollis, diam massa suscipit metus, ut ornare tellus arcu nec orci.

Pellentesque bibendum dignissim tincidunt. Morbi vel sem lacus. Cras vitae laoreet eros. Aenean hendrerit ante semper, auctor ligula et, interdum sapien. Duis placerat urna at velit tincidunt commodo. Fusce condimentum mauris ut ornare euismod. Duis iaculis, augue in varius pretium, justo ligula volutpat est, et ornare dui nibh a sem. Quisque sit amet ultricies tortor.

Praesent egestas tincidunt massa convallis elementum. Fusce ac nisl sed arcu placerat commodo ut a lacus. Donec eget blandit lacus. Vivamus ac efficitur nunc. Nulla facilisi. Phasellus vel ipsum tempus, imperdiet dolor quis, rhoncus magna. Duis lobortis, nisl non lobortis faucibus, risus metus ullamcorper mauris, a ultricies quam nibh vitae sapien. Nulla facilisi. Donec luctus in libero vel pharetra. Maecenas mollis quam libero, eget pellentesque risus convallis at. Morbi laoreet vitae urna id accumsan. Etiam eu porttitor dolor. Curabitur eu sagittis augue. Phasellus at laoreet lacus. Donec interdum aliquet consectetur.

Etiam vestibulum sapien in metus iaculis bibendum. Fusce aliquet sodales leo, et interdum nisl gravida non. Quisque eget lobortis metus, ac euismod ipsum. Cras ac gravida purus. Integer erat orci, feugiat eget tortor sit amet, semper fringilla tortor. Duis luctus at magna sodales efficitur. Donec enim nulla, tempor vel dictum nec, porta vel dolor. Vivamus semper dui tortor. Curabitur turpis mi, mollis a sodales sodales, feugiat eu nisi. Pellentesque non fringilla nisl. Donec at dapibus libero, sed tempor arcu. Pellentesque velit ante, interdum in orci at, feugiat viverra orci. Quisque egestas a tortor et ullamcorper. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nullam ut nunc tempor, dictum orci eu, pharetra enim.

Sed accumsan sem ipsum. Integer id dolor quis massa tempor congue ac ut nisi. Pellentesque nulla lectus, efficitur non sagittis quis, ornare vel nisl. Proin tempor ullamcorper turpis, et hendrerit est fermentum rutrum. Ut ligula nisi, varius quis sodales at, euismod et diam. Mauris vel sem a mi eleifend fringilla. Suspendisse magna magna, lacinia sit amet nisl eu, laoreet ultricies erat. Suspendisse non orci ante. Aliquam interdum ac lacus eget ornare. Vestibulum dictum felis vitae hendrerit interdum. Duis quis tempus urna.
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis tempus arcu a nisl bibendum interdum sed in velit. Etiam semper sem ac nisl rhoncus, at molestie lectus laoreet. Phasellus pulvinar libero mi, a aliquet felis condimentum ut. Morbi massa libero, finibus vitae pellentesque vitae, dignissim sed purus. Ut volutpat consequat commodo. Praesent consequat eget mauris sed viverra. Etiam ac dui vel turpis rutrum tincidunt eu vitae orci. Nunc rhoncus molestie eros nec aliquet. Vestibulum et blandit orci, vitae molestie massa. Morbi hendrerit orci ac interdum tincidunt. Nulla facilisi. Nulla blandit purus eget mattis eleifend. Etiam blandit, enim vel porttitor mollis, diam massa suscipit metus, ut ornare tellus arcu nec orci.

Pellentesque bibendum dignissim tincidunt. Morbi vel sem lacus. Cras vitae laoreet eros. Aenean hendrerit ante semper, auctor ligula et, interdum sapien. Duis placerat urna at velit tincidunt commodo. Fusce condimentum mauris ut ornare euismod. Duis iaculis, augue in varius pretium, justo ligula volutpat est, et ornare dui nibh a sem. Quisque sit amet ultricies tortor.

Praesent egestas tincidunt massa convallis elementum. Fusce ac nisl sed arcu placerat commodo ut a lacus. Donec eget blandit lacus. Vivamus ac efficitur nunc. Nulla facilisi. Phasellus vel ipsum tempus, imperdiet dolor quis, rhoncus magna. Duis lobortis, nisl non lobortis faucibus, risus metus ullamcorper mauris, a ultricies quam nibh vitae sapien. Nulla facilisi. Donec luctus in libero vel pharetra. Maecenas mollis quam libero, eget pellentesque risus convallis at. Morbi laoreet vitae urna id accumsan. Etiam eu porttitor dolor. Curabitur eu sagittis augue. Phasellus at laoreet lacus. Donec interdum aliquet consectetur.

Etiam vestibulum sapien in metus iaculis bibendum. Fusce aliquet sodales leo, et interdum nisl gravida non. Quisque eget lobortis metus, ac euismod ipsum. Cras ac gravida purus. Integer erat orci, feugiat eget tortor sit amet, semper fringilla tortor. Duis luctus at magna sodales efficitur. Donec enim nulla, tempor vel dictum nec, porta vel dolor. Vivamus semper dui tortor. Curabitur turpis mi, mollis a sodales sodales, feugiat eu nisi. Pellentesque non fringilla nisl. Donec at dapibus libero, sed tempor arcu. Pellentesque velit ante, interdum in orci at, feugiat viverra orci. Quisque egestas a tortor et ullamcorper. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nullam ut nunc tempor, dictum orci eu, pharetra enim.

Sed accumsan sem ipsum. Integer id dolor quis massa tempor congue ac ut nisi. Pellentesque nulla lectus, efficitur non sagittis quis, ornare vel nisl. Proin tempor ullamcorper turpis, et hendrerit est fermentum rutrum. Ut ligula nisi, varius quis sodales at, euismod et diam. Mauris vel sem a mi eleifend fringilla. Suspendisse magna magna, lacinia sit amet nisl eu, laoreet ultricies erat. Suspendisse non orci ante. Aliquam interdum ac lacus eget ornare. Vestibulum dictum felis vitae hendrerit interdum. Duis quis tempus urna.

Comment: Hey Temani, thanks for the help. I'm wanting the top right to be bigger than the bottom left. Also want them both to be corner triangles. Is this possible?
Comment: ah ok, didn't know you want triangle, will update the answer ;)
Comment: And the triangles will stay in the same position on page resize and enlarge/decrease in size?
Comment: "enlarge/decrease" in size, you mean what exactly ?


if files mtime is less than x amount. print those files

Question: I am able to print mtime attribute of files. I am only concerned with files modified in say the last xxxx amount of minutes. I touched files in the directory so i know there are new files there.
file_list_attr = sftp.listdir_attr('/path')
fdir = sftp.listdir(path=source)

for f in file_list_attr:
    print "name=%s, modified date=%s, size=%s" % (f.filename, f.st_mtime,f.st_size)

mt = f.st_mtime
now=dt.datetime.now()
while f.st_mtime == now-dt.timedelta(minutes=2120):
   print 'You have something here'
else:
    print 'nada'

Answer: The problem seems to be in how you check the mtime.
Shouldn't this line:
while f.st_mtime == now-dt.timedelta(minutes=2120):

be like:
while f.st_mtime > now-dt.timedelta(minutes=2120):

Or better:
delta = dt.timedelta(minutes=2120)
while f.st_mtime > dt.datetime.now() - delta:
    # ...

Because if you don't recalc your now-date I don't see the point of looping.
Comment: Poggi, I will give it a try. Thanks for helping a newbie
Comment: The issue seems to be is that datetime now can not iterate over an int. TypeError: can't compare datetime.datetime to int


Geometry Problem MCQ

Question:
$AD$ bisects the angle $A$ of $\triangle ABC$ and meets $BC$ at $D$ such that $BD/DC = AB/AC$. If $BC = k$, $CA = l$ and $AB = m$, then the length of $DC$ is:
  a) $$kl/(m+l)$$
  b) $$k(m+l)/l$$
  c) $$km/(m+l)$$
  d) $$k(m+l)/m$$

I used the given equation to solve for $DC$ and took $DC$ as $x$ and $BC$ as $(k-x)$ and got the following quadratic equation:
$$x^2 + lx/m - lk/m = 0$$
whose root is
$$\frac{-l + \sqrt{l^2 + 4lmk}}{2m}$$
I am not able to solve from here.
Can anyone suggest a way to proceed?
Thanks.
Answer: That seems quite complicated. The answer that I got is option a, that is $\frac{kl}{m+l}$
I did this using the following diagram: Labelled Triangle Diagram
Now, the question give us that $\frac{BD}{DC}$=$\frac{AB}{AC}$
Using the variables mentioned in the question as well as the diagram above, we get: $$\frac xy=\frac ml$$
Multiplying both sides by $y$ as well as adding $y$ on both sides give us: $$x+y=\frac{my}{l} + y$$
Now, we bring back the assumption that $x+y=k$ and take $y$ common on the other side, which give us: $$k=y(\frac{m+l}{l})$$
Now, rearranging the formula gives us the following: $$DC=y=\frac{kl}{m+l}$$
Answer:
The right answer is a), at it follows from the equation
$$\frac{k-x}x = \frac{m}l$$
which is nothing else as the rewriting of the given relation
$$\frac {BD} {DC} = \frac {AB} {AC}$$
as  $BD = BC - DC \space(= k - x$).
Answer: $$\frac{BD}{AB}=\frac{DC}{AC}=\frac{BD+DC}{AB+AC} \Rightarrow \frac{x}{l}=\frac{k}{m+l} \Rightarrow x=\frac{lk}{m+l}$$
The first term equality is a standard property of proportion.

Geometry Problem MCQ


New to programming php, and have seen similar problems

Question: So currently I'm trying to fix up some old code for a stats server for a game (that is definitely outdated, and has been replaced recently with a new version).  MUCH of the code is deprecated, so it's kind of guesswork on fixing it right, but I found a section thats completely broken that I have no idea how to fix, and it's causing a fatal error.
The code is as follows
for ($i=0; $i<$armyCount; $i++)
{
    $summary['total']['time'] += $armies[0]['time'.$i];
    $summary['total']['win'] += $armies[0]['win'.$i];
    $summary['total']['loss'] += $armies[0]['loss'.$i];
    $summary['total']['score'] += $armies[0]['score'.$i];
    $summary['total']['best'] += $armies[0]['best'.$i];
    $summary['total']['worst'] += $armies[0]['worst'.$i];
    $summary['total']['brnd'] += $armies[0]['brnd'.$i];
}

The errors I get are as follows
Notice: Uninitialized string offset: 0 in C:\xampp\htdocs\dontneedthis\playerstats.inc.php on line 136

Fatal error: Cannot use string offset as an array in C:\xampp\htdocs\dontneedthis\playerstats.inc.php on line 136

I've seen similar questions asked, and seen how they were resolved, but I don't fully understand how it was done, so don't quite know how to go about fixing this one.  Any assistance would be awesome, and I fully intend to release the bugfixed and fully working code (whenever I get that done) to the community that remains.
Comment: This error message indicates that index 0 of $armies is not set. With your code snipped the source could only be guessed.
Comment: Which one is the line the error message is refering to? And what do `$summary` and `$armies` look like?
Comment: should use : for ($i=0; $i<count($armies); $i++)
Answer: It looks like your $armies[0]['time'.$i] is initialized as an empty string and not as an array (likely $armies= "").
Notice: Uninitialized string offset: 0

That means that php tries to access your string-variable $armies as an array. If the string is non-empty then this would result in getting single letters from that string. But it seems that $armies is an empty string and so getting the letter with index 0 is not possible.
Fatal error: Cannot use string offset as an array

means that the result of the operation above (which showed the notice) cannot be accessed as an array. Remember that $armies is a astring and the first letter of the string was accessed and the result of this attempt will be accessed as an array.
Try resolving how the $armies variable is filled and why its filled the wrong way.
Answer: $armies is an empty string, and you are treating it as any array, in an unrecoverable way.
Show us what $armies should look like, what you get when you var_dump($armies);, and the code from where you assigned it, and we'll help you work out what went wrong.


Underscore.js - Uncaught SyntaxError: Unexpected token ) while generating template with variables

Question: I'm trying to learn Backbone.js with Underscore.js and got into trouble. I'm using Grails as a server framework, so the Underscore.js syntax <%= %> is not possible. I want to change it to {{}} style. My Javascripts are separated in many files, each representing either a View or Model for every objects I need. Here is the code for my View:
$(function () {

    _.templateSettings = {
        interpolate : /\{\{(.+?)\}\}/g,
        evaluate : /\{!(.+?)!\}/g
    };

    APP = window.APP || {};

    APP.PlaceView = Backbone.View.extend({
        initialize:function () {
            this.render();
        },
        el:"#place-form",
        formTemplate:_.template($('#search-template').html()),
        render:function () {
            //Pass variables in using Underscore.js Template
            var variables = { street:"Ulica" };

            this.$el.html(this.formTemplate({ "street":"Ulica" }));
        }
    });

    var view = new APP.PlaceView();
});

And the template:

This code throws Uncaught SyntaxError: Unexpected token ) error. But when I delete the _.templateSettings part, everything is ok, but I don't have the variables.
Thanks a lot.
Comment: I'm getting the exact same error, I'm using handlebar's syntax because I'm using HAML, any idea how you solved this?
Answer: I believe it's showing that error because of this line:

Underscore is trying to replace that with a variable that doesn't exist, thus throwing an error.
Comment: this was driving me crazy! It shouldn't be in the sample code


Video playback works only as root using a Nvidia card

Question: That is, video playback with anything: chrome (html 5), firefox (flash), vlc, totem, smplayer... whatever. It works only if the software is started as root otherwise it freezes at the begin Interesting enough, in chrome, you can move the slider to whatever position and see the current frame updated.
However the video stay still. This started to happen a couple of days ago after an unidentified update. Relevant output from chrome run as normal user gives some hint:
NVIDIA: could not open the device file /dev/nvidia0

No output coming from firefox or vlc
$ ls -l /dev/nvidia0
crw-rw-rw- 1 root root 195, 0 nov  8 21:18 /dev/nvidia0

Comment: How did you resolve this? Did you change /dev/nvidia0 to be in group 'video'?
Answer: Removing nvidia proprietary drivers and using nouveau. Also I had to purge all packages of nvidia proprietary drivers otherwise I was getting wrong resolution on the display.
Answer: Normally your /dev/nvidia0 should be accessible to the video group. If you executed Totem (or any other player) you will notice a line like this:

NVIDIA: could not open the device file /dev/nvidia0 (Operation not permitted).

Normally, you should be able to workaround adding yourself to the group video and rebooting your system.
sudo adduser Hal video

Is really weird that the /dev/nvidia0 file is owned by root.


containable and extra id field

Question: Suppose I have a tipical Post belongsTo User belongsTo Group scenario
suppose I want to filter the Posts using some conditions and I want to know how many distinct groups are involved (I just need the list of group_id)
I did something like
$this->Post->find(
    'all'
    array(
        'fields' => array('DISTINCT User.group_id'),
        'conditions' => array ( ... ), // here go my search criteria about posts
        'contain' => array('User')
    )
);

I expected a query like
SELECT DISTINCT User.group_id FROM posts AS Post LEFT JOIN users AS USER ON ...

But when using contains cake introduce an extra field so the query becomes
SELECT DISTINCT User.group_id, User.id FROM posts AS Post LEFT JOIN users AS USER ON ...

and I don't get the expected result.
I solved using manual joins, but is there any way to force cake not to add that id field for the contained table?
Answer: You should be able to accomplish what you want by turning off $autoFields on the Containable behavior.
$this->Post->Behaviors->load('Containable', array('autoFields' => false));

See the book for more info: http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html#containablebehavior-options
Comment: It works! Thanks a lot. I still don't like the fact that I have to set the value of `autoFields` when loading the behavior and I can't set it in my find options but it's much better than using manual joins

containable and extra id field


How do I get the Monkey achievement?

Question: The "Monkey" achievement has the description

Unleash the nibbling totem monkey head in "babylonian"

I have completed "babylonian" by two different paths: one where I press the one visible button, and one where I don't and I can get all of the prisms. Neither made the achievement unlock. What do I have to do to the it?
Answer: You have to press the tiles at the top of the structure in the right order so they don't play a noise when going over them. The tile at the bottom left of the screen counts as the first one. This involves skipping over a few tiles and entering the colored finish zone. If you make a mistake you can simply go back to the first tile at the bottom left to reset everything.
This is the actual order - N marks north.
<code> ___________________
| 4 |   | N |   |   |
|___|___|___|___|___|
| 2 | o | o | o |   |
|___|___|___|___|___|
| 5 | o | X | o |   |
|___|___|___|___|___|
| 3 | o | o | o |   |
|___|___|___|___|___|
| 1 |   |   |   |   |
|___|___|___|___|___|
</code>

How do I get the Monkey achievement?


autoincrement udf in hive

Question: I have created a udf in hive to add auto increment column in hive.
import org.apache.hadoop.hive.ql.exec.UDF;

public class AutoIncrUdf extends UDF {
    int Value;

    public int evaluate() {
        Value++;
        return Value;
    }
}

I have created a temporary function temp while using on my table as
Select temp() from table1;

it is giving all rows as:
 1
 1
 1
 1

And so on. But I want it as
1
2
3
4

Comment: hi @bat_rock I am stuck at the same problem. Commenting to check if you found any solution in last 4 years :)
Answer: I think it's better to use below code for autoincrement udf in hive:
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.hive.ql.udf.UDFType;

@UDFType(deterministic = false)
public class AutoIncrementUDF extends UDF {

    int ctr ;

    public int evaluate() {
        ctr++;
        return ctr;
    }
}

Comment: Welcome to SO. Take a tour http://stackoverflow.com/tour to get idea on how to write better answer. This is 3 years old question and your answer isn't different then the one below from @neerajyadav? Something changed in meanwhile?
Answer: It should work. One instance of UDF class is created per call. Maybe try static int Value; .. GL
Comment: Yeah, this should work. But be ware this type of UDF depends on all the rows doing through one mapper/reducer to have rows perfectly numbered. Likely not your specific problem here since you end up with dups not all the same number.
Answer: Add stateful attribute to your class:
@UDFType(stateful = true)
public class AutoIncrUdf extends UDF {
    ...
}

The addition of annotation @UDFType(stateful = true) is required otherwise counter value will not get increment in the Hive column, it will just return value 1 for all the rows but not the actual row number. This is the same issue you are facing.
Answer: It worked for me.
Try out the below :
http://svn.apache.org/repos/asf/hive/trunk/contrib/src/java/org/apache/hadoop/hive/contrib/udf/UDFRowSequence.java
CREATE TEMPORARY FUNCTION rowSequence AS .UDFRowSequence';
SELECT rowSequence(100) AS id, field1, field2 from 'table' where 'condition';
Comment: I had to use this command to get it to work: `CREATE TEMPORARY FUNCTION rowSequence AS 'org.apache.hadoop.hive.contrib.udf.UDFRowSequence';`

autoincrement udf in hive


How to integrate $\int{ dx \over \sqrt{1 + x^2}}$

Question: How to integrate  $dx \over \sqrt{1 + x^2}$?
Answer should be $\log ( x + \sqrt{1 + x^2})$
Please help as possible...
Thank you
Comment: $x = \sinh t$ works well.
Comment: Make the substitution $u=\sqrt{1+x^2}$
Comment: Please use parentheses for grouping sqrt 1 + x^2 could easily be $\sqrt 1 + x^2$ instead of $\sqrt {1+x^2}$.  Better, use MathJax.  A tutorial is [here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)
Comment: This is a very standard integral and you could have differentiated $\log(x+\sqrt{1+x^{2}})$ and got the result.
Comment: One can learn how to recognize when an integral begs for a trigonometric substitution.  That would have gotten you started here.  (That's not necessarily the only way to do it, though.)
Comment: See also http://math.stackexchange.com/questions/179129/how-to-integrate-frac1-sqrt1x2-using-substitution
Answer: Let $\displaystyle I = \int \dfrac{1}{\sqrt{1+x^2}}~\mathrm dx.~ $Let $\tan u = x.$ Then  $\sec^2 u ~\mathrm du = \mathrm dx,~u = \arctan x$  and $$ \begin{align*}I  & = \int \sec u~ \mathrm du = \log (\tan u + \sec u)+C\\
& = \log\left(x + \sqrt{1 + x^2}\right) + C~.
\end{align*}$$
Feel free to ask questions if anything is unclear.
Answer: We have
$$\int \frac{1}{\sqrt{1+x^2}}\, dx.$$
We make the following substitution. Let
$$
\begin{align*}
x&=\tan \theta \\
dx &= \sec^2 \theta \, d \theta\\
1+x^2&=1+\tan^2 \theta \\
&=\sec^2 \theta.
\end{align*}
$$
Hence our integral becomes
$$
\begin{align*}
\int \frac{1}{\sqrt{1+x^2}}\, dx &= \int\frac{\sec^2 \theta \, d \theta}{\sqrt{\sec^2 \theta}}\\
&=\int \sec \theta \, d \theta \\
&=\ln |\sec \theta + \tan \theta|+c.
\end{align*}
$$
For the back substitution, since
$$\tan \theta = \frac{x}{1},$$
we can form a right triangle with side opposite $\theta$ equal to $x$, and side adjacent to $\theta$ equal to $1$. Hence the hypoteneuse will have length $\sqrt{1+x^2}$. We can now read straight from the right triangle and back substitute,
\begin{align*}
\ln |\sec \theta + \tan \theta|+c &= \ln \left | \frac{\sqrt{1+x^2}}{1}+\frac{x}{1} \right |+c\\
&=\ln \left | \sqrt{1+x^2}+x \right |+c.
\end{align*}
Answer: A possibility is to use the following properties of the inverse hyperbolic function $\operatorname{arcsinh}x$:

$(\operatorname{arcsinh}x)' =\dfrac{1}{\sqrt{1+x^{2}}}\qquad$ (Wikipedia entry)
$\operatorname{arcsinh}x =\ln \left( x+\sqrt{x^{2}+1}\right)$ (Wikipedia entry)
Answer: Let $x=iy$, where $i=\sqrt{-1}$ . Then the integral becomes $\displaystyle\int\frac{i\cdot dy}{\sqrt{1-y^2}}=i\arcsin y=i\arcsin\frac xi$ $=i\cdot\arcsin(-ix)=i\cdot(-i)\cdot\text{arcsinh }x=\text{arcsinh }x=\ln(x+\sqrt{1+x^2})$ . See here and here for more details.
Answer: Let $\displaystyle 1+x^2=y^2\Rightarrow \sqrt{1+x^2} = y,$ and $2xdx = 2ydy$
$$\displaystyle xdx = ydy\Rightarrow \frac{dx}{y} = \frac{dy}{x} = \frac{d(x+y)}{(x+y)}$$ (Using Ratio and Proportion).
Now $$\displaystyle \int \frac{1}{\sqrt{1+x^2}}dx = \int \frac{dx}{y} = \int \frac{d(x+y)}{(x+y)} = \ln \left|x+y\right|+C$$
So $$\displaystyle \int \frac{1}{\sqrt{1+x^2}}dx = \ln \left|x+\sqrt{x^2+1}\right|+\mathbb{C}$$


OpenCV 2.1 Memory leak on simple video streaming on Mac OSX

Question: Even just doing the most basic video streaming causes a memory leak for me.
cvNamedWindow("1",0);
CvCapture *fc = cvCaptureFromCAM(0);
IplImage *frame = NULL;
CvSize frameSize;
frameSize.height = cvGetCaptureProperty(fc, CV_CAP_PROP_FRAME_HEIGHT);
frameSize.width = cvGetCaptureProperty(fc, CV_CAP_PROP_FRAME_WIDTH);

while (1) {
    IplImage *wrkImage = NULL;

    frame = cvQueryFrame(fc);

    if (!frame)
        break;

    wrkImage = cvCreateImage(frameSize, IPL_DEPTH_8U, 3);
    cvCopy(frame, wrkImage, NULL);

    cvShowImage("1", wrkImage);

    char c = cvWaitKey(33);
    if (c == 27) {
        break;
    }

    cvReleaseImage(&wrkImage);
}

Apparently according to the book "Learning OpenCV", I'm not supposed to release "frame" since it's managed by openCV and I can "expect problems if I do".  It does indeed cause problems if I release the frame pointer once I've called cvQueryFrame.  The book also suggests copying the image pointed to by cvQueryFrame elsewhere to work on it since cvQueryFrame presumably recycles the same chunk of memory repeatedly.  Hence wrkImage which I do release at the end of each frame cycle.  The program crashes after a few mins, and leaks memory like crazy!  Leads me to believe something major is getting leaked like entire frames.  I'm wondering if anyone uses OpenCV 2.1 on the Mac for video stuff and has found this to be an issue as well.  Or if anyone can see a gaping hole in my code that I'm missing.
Any advice from OpenCV guru's out there would be much appreciated!
Edit:  After carefully stepping through the program and examining memory, I suspect the issue is with cvShowImage().  cvShowImage seems to allocate about a frame's worth of memory that never seems to get reclaimed.  Then found this link  OpenCV cvShowImage Memory Leaks OSX that seems to agree with my suspicions.  Might be close to a solution here...  Just glad to see I'm not crazy!
UPDATE:  The Macports OpenCV is fine now (and has been for a few months now.  Just thought I should post that here so people aren't getting discouraged from using macports for their OpenCV build/install.  Macports is a great way to install OpenCV.
Comment: Oh and I'm using a Mac Ports installation of OpenCV 2.1 that I installed 2 weeks ago
Answer: There is nothing wrong with the code I provided.  The current MacPorts build of openCV has a memory leak in the cvShowImage() function.  I downloaded and built the most recent version manually, and it no longer leaks memory.
For anyone who reads this, if your openCV program is curiously leaking memory, and you installed using MacPorts, I'd suggest downloading the source and building manually using cmake.
Answer:
You are trying to get capture properties of the camera before calling cvQueryFrame and depending on the circumstances that may not result in getting the correct properties.  Doesn't look like that is the issue, just FYI.
There is no reason to create a new IplImage.  If all you are trying to do is display it in a window, consider changing your capture code.

New Capture Loop:
while (true) {

    frame = cvQueryFrame(fc);

    if (!frame)
        break;

    cvShowImage("1", frame);

    char c = cvWaitKey(33);
    if (c == 27) {
        break;
    }

}

Like you mentioned in your EDIT, the problem stems cvShowImage followed immediately by cvReleaseImage, unless you have a reason for doing it, just remove it.
Comment: This obviously isn't all I was trying to do.  My code snippet there was to show that even in an extremely basic situation, there is a memory leak.  So yes, there is a reason for doing it, namely that you're supposed to copy image data into a new IplImage before performing operations on it.
Comment: Just trying to help man, if you don't want suggestions then don't ask a question.
Comment: wasn't flaming you, just pointing out that there is indeed a reason for copying the image.  thx for the response