text:
Q: Finding the most frequent character in a string javascript Assuming I have the following string "355385". I need a simple JavaScript that can tell me that the most mentioned character is 5. Thank you in advance.
I tried with this one but no results.
var exp = '355385' ;

var exps =exp.split("");

var expCounts = { };

for (var i=0;i<exp.length;i++)

{expCounts["_" + exps[i]] = (expCounts["_" + exps[i]] || 0) + 1 ;

if (expCounts==3) exps=exps[i]; }; exps;

A: var getMax = function (str) {
 var max = 0,
     maxChar = '';
  str.split('').forEach(function(char){
    if(str.split(char).length > max) {
        max = str.split(char).length;
        maxChar = char;
     }
  });
  return maxChar;
};

logs
getMax('355385') //5;

getMax('35538533') //3;

in equal case it will return first number
getMax('3553') //3;

A: var string  = "355385",
    counter = {};

for (var i = 0, len = string.length; i < len; i += 1) {
    counter[string[i]] = (counter[string[i]] || 0) + 1;
}

var biggest = -1, number;
for (var key in counter) {
    if (counter[key] > biggest) {
        biggest = counter[key];
        number = key;
    }
}

console.log(number);
# 5

A: var exp = '355385';
var findMostFrequent = function (string) {
    var chars = {}, first = string.charAt(0);
    chars[first] = 1;
    var maxChar = first, maxCount = 1;

    for (var i = 1; i < string.length; i++) {
        var char = string.charAt(i);
        if (chars[char]) {
            chars[char]++;
        } else {
            chars[char] = 1;
        }
        if (chars[char] > maxCount) {
            maxChar = char;
        }
    }
    return maxChar;
};

A: Another Solution
function maxChar(str) {

        const charMap = {};
        let max = 0;
        let maxChar = '';

        for(let char of str){
            if(charMap[char]){
                charMap[char]++;
            }else{
                charMap[char] = 1;
            }
        }

        for(let char in charMap){
            if(charMap[char] > max){
                max = charMap[char];
                maxChar = char;
            }
        }

        return maxChar;
}

Result:
 maxChar('355385')
  "5"

A: Another way to get the most frequent character in a string - sort frequency map into an array and then return the first (greatest) value from that array:
function highest (string) {
  let array = Array.from(string);
  let frequencyMap = {};
  array.forEach((value, index) => {
    if (!frequencyMap[value]) {
      frequencyMap[value] = 0;
    }
    frequencyMap[value] += 1;
  })
  let frequencyArray = Object.entries(frequencyMap);
  frequencyArray.sort((a, b) => {
    if (a[1]  b[1]) {
      return -1;
      }
      return 0;
    });
  return(frequencyArray[0][0]);
}

console.log(highest("hello World"));

returns "l"

A: None of the answers above take into consideration that JavaScript internally uses UTF-16

const s = "";

function getMostFrequentChar(s) {
  const len = s.length;
  const freq = {};
  let maxFreq = 0;
  let maxChar;
  for (let i = 0; i < len; ++i) {
    const isPair = (s.charCodeAt(i) & 0xF800) == 0xD800;
    const c = isPair ? s.substr(i++, 2) : s[i];
    const f = (freq[c] || 0) + 1;
    freq[c] = f;
    if (f > maxFreq) {
      maxFreq = f;
      maxChar = c;
    }
  }
  return {maxFreq, maxChar, freq}
}

console.log(getMostFrequentChar(s));

Note: the code above assumes the string is valid UTF-16. It's possible to construct a string that is not valid UTF-16 in which case maybe you could change isPair to
const isPair = len - i > 1 &&
               s.charCodeAt(i    ) & 0xF800) == 0xD800 &&
               s.charCodeAt(i + 1) & 0xF800) == 0xD800;

But it's not clear what a character with an invalid UTF-16 value means.
It also won't handle more funky unicode
s = ""

There are many graphmemes that take multiple unicode code points
Also, splitting the string using split is SSSSSSLLLLLOOOOWWWW and a huge memory hog if the string is long.

A: Here is yet another answer to this question:
For this I have considered that the character can be of whatevert kind except a space
function findHighestFreqInString(str) {
    if (!str) return null
    let cleanedStr = str.replace(/\s/g, '') //assumes no spaces needed
    if (cleanedStr.length === 0) return null
    let strObj = {}
    let topChar = ''
    for (let val of cleanedStr) {
        strObj[val] = (strObj[val] || 0) + 1
        if (topChar === '' || strObj[val] >= strObj[topChar]) topChar = val
    }
    return topChar
}

Here is how you would use it:
findHighestFreqInString('my name is Someone') // returns: e
findHighestFreqInString('') // returns: Null
findHighestFreqInString('    ') // returns: Null

A: This will loop over every character in the string and keep track of each character's count and the character with the maximum count:
var exp = '3553853335' ;
var expCounts = {};
var maxKey = '';
for(var i = 0; i < exp.length; i++)
{
    var key = exp[i];
    if(!expCounts[key]){
     expCounts[key] = 0;
    }
    expCounts[key]++;
    if(maxKey == '' || expCounts[key] > expCounts[maxKey]){
        maxKey = key;
    }
}

console.debug(maxKey + ":" + expCounts[maxKey]);

Update:
Here is an ES6 version that will handle strings where multiple character have the same max count
function maxCount(input) {
    const {max, ...counts} = (input || "").split("").reduce(
    (a, c) => {
        a[c] = a[c] ? a[c] + 1 : 1;
        a.max = a.max  v === max);
}

Example (please excuse the crude output):
maxCount('--aaaa1111--').join(' | ').replace(/,/g, ':');

outputs 1:4 | -:4 | a:4

A: Here is:
let str = '355385';
function mostFrequentCharacter(str) {
        let charactersArr = str.split(''),
            bins = {};

        charactersArr.map(el => bins[el] = (bins[el] || 0) + 1);
    return Object.keys(bins).map(key => ({
            name: key,
          count: bins[key]
    })).sort((a, b) => b.count - a.count)[0];
}

A: You can use the following solution to find the most frequent character in a string:
function getMostRepeatedCharacter(string) {
    return string.split('').reduce((acc,char)=>{
        let len = string.split(char).length - 1;
        return len > acc[1] ? [char,len] : acc
    },['',0])[0]
}

getMostRepeatedCharacter('wediuaududddd') // d

A: Want to share this ES6 functional approach. Please provide your input.
function maxChar(myStr) {
  let charObj = {};
  return [...myStr].reduce((_, char) => {
    if (char in charObj) charObj[char]++;
    else if (char !== " ") charObj[char] = 1;
    return Object.keys(charObj).reduce((a, b) => {
      return charObj[a] > charObj[b] ? a : b;
    });
  });
}

A: The simplest approach will be like this:
function maxChar(str) {
  const charMap = {};
  let max = 0;
  let maxChar = '';

start by making an object of words and how many they repeated, to do that we have to loop through the string using for of and implementing the conditions:
  for (let char of str) {
    if (charMap[char]) {
      charMap[char]++;
    } else {
      charMap[char] = 1;
    }
  }

and now loop through the object using for in
  for (let char in charMap) {
    if (charMap[char] > max) {
      max = charMap[char];
      maxChar = char;
    }
  }

  return maxChar;
}

A: this is another (bizarre) way
It substitute the current character with blank for check how many times is present in the string making the difference of length with original pattern
var str = "355385";
var mostLength = 0;
var characterMostLength;
for(t = 0; t< 10; t++)
{
    var res = str.length - str.replace(new RegExp(t, "g"), "").length;
    if (res > mostLength){
        characterMostLength = t;
        mostLength = res;
    }
}

A: function solution(N) {
    var textToArr = N.split('');
    var newObj = {};
    var newArr = [];

    textToArr.map((letter) => {
        if(letter in newObj){
            newObj[letter] = newObj[letter]+1;
        } else {
            if(letter !== ' '){
               newObj = Object.assign(newObj, {[letter]: 1})
            }
        }
    });

    for(let i in newObj){
        newArr.push({name: i, value: newObj[i]})
    }

    var res = newArr.sort((a,b) => b.value-a.value)[0];
    return res.name+':'+res.value
}

solution("hello world");

A: this is a simple Idea that only includes one pass-through with a hashmap. The only thing this does not do is handle several max numbers. I really hope you enjoy my solution :) .
function maxChar(str) {
    //Create the output and the hashmap
    let m = {}, ans

    //Loop through the str for each character
    //Use reduce array helper because of the accumulator

    str.split('').reduce((a, c) => {

        //Increments Map at location c(character) unless it does not already exist

        m[c] = m[c] + 1|| 1

        //This checks to see if the current passthrough of m[c] is greater than or equal to the accumulator, if it is, set the answer equal to the current character. If it's not keep the ans the same.

        ans = m[c] >= a ? c : ans

        //Only increment the accumulator if Map at location c(character) is greater than the accumulator. Make sure to return it otherwise it won't increment.

        return a = m[c] > a ? a + 1 : a
    }, 1)

    //Lastly return the answer
    return ans
}

A: Simplest way to find maximum number of occurring character in string
var arr = "5255522322";
    var freq:any = {};
    var num;
    for(let i=0;i<arr.length;i++) {
      num = arr[i];
    freq[num] = freq[num] >= 1 ? freq[num] + 1 : 1;
    }
    var sortable:any = [];
    for(let i in freq)
    {
      sortable.push(i);
    }
    var max = freq[sortable[0]];
     var data:any = "";
   var value = sortable[0];
    for(let i=0;i<sortable.length;i++) {

      if(max > freq[sortable[i]]){
        data = "key" + value + " " + "value" + max;
      }else{
        value = sortable[i]
        max = freq[sortable[i]];
      }
    }

    console.log(data);

A:

function maxChara(string) {
  charMap = {};
  maxNum = 0;
  maxChar = "";

  string.toString().split("").forEach(item => {
    if (charMap[item]) {
      charMap[item]++;
    } else {
      charMap[item] = 1;
    }
  });

  for (let char in charMap) {
    if (charMap[char] > maxNum) {
      maxNum = charMap[char];
      maxChar = char;
    }
  }
  return maxChar;
}

let result = maxChara(355385);
console.log(result);

A: Here str will the string that needs to be verified.
function maxCharacter(str){

let str1 = str; let reptCharsCount=0; let ele='';let maxCount=0;
let charArr = str1.split('');
for(let i=0; i< str1.length; i++){
    reptCharsCount=0;
    for(let j=0; j< str1.length; j++){
        if(str1[i] === str1[j]) {
            reptCharsCount++;
        }
    }

    if(reptCharsCount > maxCount) {
        ele = str1[i];
        maxCount = reptCharsCount;
    }
}
return ele;

}
input
maxCharacter('asdefdfdsdfseddssdfsdnknmwlqweeeeeeeesssssssssssseeee');
output
"s"

A: function freq(str) {
        var freqObj = {};
        str.forEach((item) => {
            if (freqObj[item]) {
                freqObj[item]++;
            }
            else {
                freqObj[item] = 1;
            }

        });
        return freqObj;

    }
    function findmaxstr(str) {
        let max = 0,res,freqObj;
        freqObj = freq(str.split(""));
        for(let keys in freqObj){
            if (freqObj[keys] > max) {
                max = freqObj[keys];
                res = keys;
            }
        }
        console.log(res);
        return res;
    }

findmaxstr("javasdasdsssssscript");

A:

const maxChar = (str) => {
  let obj = {};
  for (let char of str) {
    (!obj[char]) ? obj[char] = 1: obj[char]++;
  }
  maxCharcount = Math.max(...Object.values(obj));
  const key = Object.keys(obj).filter(key => obj[key] === maxCharcount);
  console.log(`Most repeated character/characters in the given string "${str}" is/are given below which repeated ${maxCharcount} times`);
  console.log(...key);
}

maxChar("355385");

A: Here is the code, where it also checks for lower and upperCase characters with the same max count and returns a Lower ASCII character as a Max.
function mostFrequent(text) {
    let charObj={}

    for(let char of text){
        if(char!==' '){
            if(charObj.hasOwnProperty(char)) charObj[char]=charObj[char]+1;
                else charObj[char]= 1
        }
    }

    let maxOccurance= Object.keys(charObj)[0], i=0;

    for(let property in charObj){
        if(i>0){
            if(charObj[property]> charObj[maxOccurance])
                maxOccurance= property
            else if(charObj[property]=== charObj[maxOccurance])
            {
                if(property<maxOccurance)
                    maxOccurance=property
                }
            }
            i++
    }

    return [maxOccurance, charObj[maxOccurance]]
}

A: let str = '355385';
let max = 0;
let char = '';
str.split('').forEach((item) => {
  let current = str.split(item).length;
  if (current > max) {
    max = current;
    char = item;
  }
});

console.log(char + ' occurred ' + (max - 1) + ' times');

A:

var exp = '35585' ;
var expCounts = { };
let maxChar = ''
let count = 0

for(let i = 0; i < exp.length; i++){
let char = exp[i]

expCounts[char] = expCounts[char] + 1 || 1

if(expCounts[char] > count){
   maxChar = char
   count = expCounts[char]

}
console.log(maxChar)
}

A: function checkNoofOccurenance(string) {
  const arr = [...new Set(string.split(''))].sort();
  const finalObj = {};
  arr.forEach((item) => {
    finalObj[item] = string.split(item).length - 1;
  });
  const item=Object.keys(finalObj).reduce((occ, toBeComapir)=>finalObj[occ]>finalObj[toBeComapir]?occ:toBeComapir)
  return item;
}

A: Using Hasmaps we can find the most frequent char and occurrence all in O(N) time complexity. Below is the code. I have used one hasmap to save all the values and while i am doing it, i am also calculating the max occurrence and the max char.

var mostFreq = function(s) {
    let myMap = new Map();
    let temp;
    let counter = 0;
    let mostFrequentChar;
    for(let i =0;i <s.length;i++){
       if(myMap.has(s.charAt(i))){
           temp = myMap.get(s.charAt(i));
           temp = temp + 1;
           myMap.delete(s.charAt(i));
           myMap.set(s.charAt(i) , temp)
           if(temp > counter){
               counter = temp;
               mostFrequentChar = s.charAt(i);
           }
       }else{
           myMap.set(s.charAt(i), 1)
       }
    }

    //if you want number of occerance of most frequent char  = counter
    //if you want list of each individual char and its occurrence = myMap
    //if you just want the char that is most frequence = mostFrequentChar;

    return mostFrequentChar;
};

A: If you want the count of the letter as well, You can do this
  const { letter, count } = input.split("").reduce(
    (acc, letter) => {
      const count = input.split(letter).length - 1;
      return count > acc.count
        ? { letter, count }
        : { letter: acc.letter, count: acc.count };
    },
    { letter: "", count: 0 }
  );

Here We are splitting the string, applying a reduce to the result. The Reduce Counts how many instances of a character are there in a string, using input.split(letter).length - 1; And if the count is greater than the previous count, updates the accumulated value to be the current value

A:

let string = "355385";

function printFirstRepeat(str){
    let output= {};
    for (let char of str) {
        char = char.toLowerCase();
        output[char] = ++output[char] || 1;
        if(output[char] > 1) return char;
    }

    return "Not Found"
}

console.log(printFirstRepeat(string));

A: Algorithm: Find maximum occurring character in a string (time complex: O(N))
I'll provide my solution to this algo-problem by utilizing the most recent concepts of javascript
const getMaxCharacter = (str) => {
  let max = 0;
  let maxChar = '';
  str.split('').forEach((char) => {
    if (str.split(char).length > max) {
      max = str.split(char).length - 1;
      maxChar = char;
    }
  });
  return `The max letter is : ${maxChar} and the max number of times it is seen is: ${max} times`;
};

Let's express an easy way of testing the function logic I wrote it:
const letter = 'Hello Student';
getMaxCharacter(letter);

In the function developed, I've used the concepts below:

*

*Arrow Function

*Anonymous Funciton

*Declare property by using let/const

*Template Literals

*forEach(); (array helper) & split()

A: This is simple and optimized solution and it returns the first occurring char if there are chars equals in counts

function maxOccurance(str) {
  let maxOccurringChar = "";
  const charMap = {};
  for (let index = 0; index < str.length; index++) {
    const ele = str.charAt(index);

    if (!charMap[ele]) {
      charMap[ele] = {
        startIndex: index,
        value: 1
      };
    } else {
      charMap[ele].value = charMap[ele].value + 1;
    }

    if (
      !maxOccurringChar ||
      charMap[maxOccurringChar].value < charMap[ele].value
    ) {
      maxOccurringChar = ele;
    } else if (
      charMap[maxOccurringChar].value === charMap[ele].value &&
      charMap[ele].startIndex < charMap[maxOccurringChar].startIndex
    ) {
      maxOccurringChar = ele;
    }
  }

  return maxOccurringChar;
}

console.log(  maxOccurance("bacdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz")
);

A: <!doctype html>

<meta charset="utf-8">
<title>Untitled Document</title>

Hello World! I am Julio!

    enter code here


text:
Q: How to test a function that receives an event? Creating tests is new to me. I'm trying to create a test for a function that receives an event. It's an onChange call if it matters, and I'm using chai.
My function:
export function handleChange(event) {
  if (isNaN(event.target.value)) {
    event.preventDefault();
    alert('input can only be a number');

  } else if (event.target.value > 5) {
    event.preventDefault();
    alert('Rating can not be over 5 stars, please try again');

  } else {
    this.setState({starRate: event.target.value});
  }

A: First, you are applying event.preventDefault() to an input. There's no 'event' to prevent in this case, so that code is essentially useless.
Second, you are using event.target.value, when only event is getting passed to your function. You're simply looking for event.value in this case.
To pass through the current input, simply pass this as a parameter into the JavaScript function. this always refers to the current element.
Here's a working example:

function handleChange(event) {
  if (isNaN(event.value)) {
    alert('The input can only be a number.');
  } else if (event.value > 5) {
    alert('Rating can not be over 5 stars, please try again.');
  } else {
    alert('The input was OK.');
  }
}
<input onchange="handleChange(this)">

When you enter an input (and then attempt to click off of the input), an alert() will be thrown.
Hope this helps! :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: integer promotion of bit-wise operation and endiannes issue Consider the following snippet from code running in the Linux kernel:
    char *d;
    u32 mask, step, val;
    ...
    /* d is initialized with valid pointer pointing at buffer,
and mask, step and val are initialized to some sane values as well. */
    ...
    val = (*d & mask) >> step;

As you see only d is of char * type, the rest are unsigned integers. I know that C performs type conversions automatically when
values of differing types participate in expressions, in this case
bit-wise operation. So, I'm assuming it is guaranteed that *d will be promoted to uint32_t as well?
If this assumption is correct, my 2nd question would be about the byte-order of 4 bytes located at memory pointed by d. I think it has to be whatever byte-order the host implements, or if it's networking, then strictly big-endian.

A: Because d has type char * it reads a single byte at the address pointed to by d.  So the expression *d has type char which has the value of the byte pointed to by d.  Endianness doesn't matter here because only a single byte is read from d.
In the larger expression *d & mask, the value *d which has type char is converted to uint32_t for use in the expression.


text:
Q: Why do you take the natural logarithm plus one? I have read in many different studies now that take the natural logarithm of one plus x.
For example, in econometrics many studies use the natural logarithm of one plus the total assets.
I do not understand why, because assets are so big anyways that adding one would not make a difference, or?
For example:
Natural Logarithm of one plus Assets(1,000,000) would be NL(1,000,001).


text:
Q: Последовательное выполнение функций Хочу после анимации убрать блок со страницы. Т.е. сначала довести до opacity=0, потом сделать display=none
Код:
$("#go").click(function(){
  $("#block").animate({
    opacity: 0.0
  }, 500 );
  $("#block").hide();
});

сразу выполняет hide(), видимо параллельно. Как заставить выполнять последовательно?
A: $("#go").click(function(){
    $("#block").animate(
        { opacity: 0.0 },
        500,
        function(){
            $("#block").hide();
        }
    );
});

или:
$("#go").click(function(){
    $.when( $("#block").animate({ opacity: 0.0 }, 500) ).then(function(){
         $("#block").hide();
    });
});

кстате, .animate({ opacity: 0.0 }, 500) эквивалентно .fadeOut(500)

*

*.animate( properties [, duration] [, easing] [, complete]): http://api.jquery.com/animate/

*jQuery.when()

*Deferred Object

*.fadeOut


text:
Q: JavaFX - ListProperty conditional binding in my code i have a tableview bound to a ListProperty.
I am able to retrieve all the data correctly but i need to apply a condition to this data set based on a specific property of each object in it.
Is it possible?
This is the model:
public class Ticket {

private String number;
private String sys_id;
private String short_description;
private String description;
private String opened_by;
private String assigned_to;         // tabella esterna
private String assignment_group;    // tabella esterna
private int incident_state;         // 2: assigned - 3: wip - 4: hold
private String sys_created_on;
private Date sys_updated_on;
private int priority;               // 1: critical
private boolean isVisible;          // per nasconderlo nella tabella riassuntiva
private boolean isAlarmed;          // per silenziare le notifiche

In the controller i have bound the tableview to a ListProperty (returned by ticketService.ticketsProperty()):
serviceNowTicket_tableView.itemsProperty().bindBidirectional(ticketService.ticketsProperty());

I just need to filter this by the ticket "isVisible" property.
Maybe via BooleanBinding?


text:
Q: How to "Re-Polish" QApplication with Same Style? Upon my qt5 application's initialization, the QApplication instance is provided with a custom style class that inherits from QProxyStyle.
This class overwrites the void polish(QPalette &palette) function in order to change the general color scheme for the application.
For example:
#include "mycolormanager.h"

void MyStyle::polish(QPalette &palette) {
    palette.setBrush(QPalette::Window, MyColorManager::getWindowColor());
    palette.setColor(QPalette::WindowText, MyColorManager::getTextColor());
    palette.setColor(QPalette::Disabled, QPalette::WindowText, MyColorManager::getDisabledTextColor());
    palette.setColor(QPalette::Base, MyColorManager::getBaseColor());
    // etc...
}

However, I wish to allow users to customize the color scheme of the application. Once the user has selected new colors, I need someway to "reapply" the style, so the function can run again and obtain the new colors from the hypothetical "color manager" class.
How would this be done?

A: Instead you can call below static function and apply the desired palette.
void QApplication::setPalette(const QPalette &palette, const char *className = nullptr);

Create the new palette object after selecting the new color scheme and just pass it to above function. You can specify classname, if you want the change to apply for a specific widget.


text:
Q: Центрирование фона в CSS Мне необходимо задать фон body так, чтобы центр фоновой картинки совпадал с центром экрана, при этом не сжимаясь при изменении размеров экрана. Есть ли возможность реализовать такое поведение фона на чистом CSS?

A: Как-то так?

body {
  background-image: url(https://picsum.photos/200/200);
  background-repeat: no-repeat;
  background-position: center;

  margin: 0;
  height:100vh;
}


text:
Q: Change PrismaticJoint engine direction Is it possible to modify the direction of the engine after the joint is created?
This is the definition of a joint:
//Define a prismatic joint
b2PrismaticJointDef jointDef;

b2Vec2 axis = b2Vec2(1.0f, 0.0f);
axis.Normalize(); //Important

jointDef.Initialize(staticBody, body, b2Vec2(0.0f, 0.0f),axis);

jointDef.localAnchorA = b2Vec2(0.0f,0.0f);
jointDef.localAnchorB = body->GetLocalCenter();
jointDef.motorSpeed = 3.0f;
jointDef.maxMotorForce = +200*body->GetMass();

jointDef.enableMotor = true;

jointDef.lowerTranslation = -2.0f;
jointDef.upperTranslation = 3.0f;
jointDef.enableLimit = true;

_horPrismaticJoint = (b2PrismaticJoint*) world->CreateJoint(&jointDef);

Inside CCTouchesBegan I tried to change the force value but it's not working:
    _horPrismaticJoint->SetMaxMotorForce(-200.0f);

The cocos distribution is cocos2d-iphone-1.0.1

A: Yes, you just need to change the speed (not the max force):
joint->SetMotorSpeed( -3.0f );

The max force describes how strong the joint motor is, so it should not be negative.


text:
Q: Alterar dados da coluna Como posso alterar os dados da coluna? Queria alterar alguns bits para false mas não sei como.
        using (SqlCommand cmdadd = new SqlCommand("INSERT into Usuarios (Cadastro) VALUES (@Cadastro)", connection2))
    {
cmdadd.Parameters.Add(new SqlParameter("@Cadastro", false));
    }

Porém não queria adicionar, queria alterar, como ficaria o código?

A: using (SqlCommand cmdadd = new SqlCommand("UPDATE Usuario set Cadastro = @Cadastro where xxx = @yyy", connection2))
{
    cmdadd.Parameters.Add(new SqlParameter("@Cadastro", false));
    cmdadd.Parameters.Add(new SqlParameter("@yyy", false));
}

A coluna xxx seria uma coluna de um identificador único da sua tabela.
não esqueça de enviar o parâmetro para fazer update.. pq update sem where é complicado :P

A: Em vez de insert use o comando Update, ficaria mais ou menos assim:
"UPDATE [Nome da Tabela SET [Nome do campo] = [Expressão] WHERE Cadastro = false"

Assim o sql vai sobrepor os valores do campo com os valores do SET e apenas no campo onde o Cadastro for False, se não usar um Where você pode acabar editando
todos da tabela, o que certamente iria ser inconveniente para você, se a explicação não foi clara, visite a fonte.
Fonte: https://sqlcomoumtodo.wordpress.com/category/update/


text:
Q: Ask user For Permission For Access Storage I made a programme for uploading files to Mysql server and code is working fine but in Marshmallow device it not working and getting error for permission. this is my error..
05-17 21:13:13.783 32468-32468/com.example.dssandroid.myapplicationupload I/MainActivity: Selected File Path:/storage/emulated/0/Android/data/net.one97.paytm/files/Download/Invoice2867017873.pdf
05-17 21:13:13.860 32468-32468/com.example.dssandroid.myapplicationupload I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@db75da1 time:94083612
05-17 21:13:15.020 32468-1040/com.example.dssandroid.myapplicationupload W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Android/data/net.one97.paytm/files/Download/Invoice2867017873.pdf: open failed: EACCES (Permission denied)
05-17 21:13:15.020 32468-1040/com.example.dssandroid.myapplicationupload W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:452)
05-17 21:13:15.021 32468-1040/com.example.dssandroid.myapplicationupload W/System.err:     at java.io.FileInputStream.<init>(FileInputStream.java:76)
05-17 21:13:15.021 32468-1040/com.example.dssandroid.myapplicationupload W/System.err:     at com.example.dssandroid.myapplicationupload.MainActivity.uploadFile(MainActivity.java:147)
05-17 21:13:15.021 32468-1040/com.example.dssandroid.myapplicationupload W/System.

now i want to know how to ask user for access storage permission before running my. i am also giving my code so please help to resolve this issue...
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private static final int PICK_FILE_REQUEST = 1;
    private static final String TAG = MainActivity.class.getSimpleName();
    private String selectedFilePath;
    private String SERVER_URL = "http://192.168.1.12:8080/uploadImage/uploadImage.php";
    ImageView resumeSelect;
    Button btnupload;
    TextView tvFileName;
    ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        resumeSelect = (ImageView)findViewById(R.id.attachment);
        btnupload = (Button)findViewById(R.id.upload);
        tvFileName = (TextView)findViewById(R.id.file_name);
        resumeSelect.setOnClickListener(this);
        btnupload.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if(v== resumeSelect){

            //on attachment icon click
            showFileChooser();
        }
        if(v== btnupload){

            //on upload button Click
            if(selectedFilePath != null){
                dialog = ProgressDialog.show(MainActivity.this,"","Uploading File...",true);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //creating new thread to handle Http Operations
                        uploadFile(selectedFilePath);
                    }
                }).start();
            }else{
                Toast.makeText(MainActivity.this,"Please choose a File First",Toast.LENGTH_SHORT).show();
            }

        }
    }

    private void showFileChooser() {
        Intent intent = new Intent();
        //sets the select file to all types of files
        intent.setType("*/*");
        //allows to select data and return it
        intent.setAction(Intent.ACTION_GET_CONTENT);
        //starts new activity to select file and return data
        startActivityForResult(Intent.createChooser(intent,"Choose File to Upload.."),PICK_FILE_REQUEST);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Activity.RESULT_OK){
            if(requestCode == PICK_FILE_REQUEST){
                if(data == null){
                    //no data present
                    return;
                }

                Uri selectedFileUri = data.getData();
                selectedFilePath = FilePath.getPath(this,selectedFileUri);
                Log.i(TAG,"Selected File Path:" + selectedFilePath);

                if(selectedFilePath != null && !selectedFilePath.equals("")){
                    tvFileName.setText(selectedFilePath);
                }else{
                    Toast.makeText(this,"Cannot upload file to server",Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    //android upload file to server
    public int uploadFile(final String selectedFilePath){

        int serverResponseCode = 0;

        HttpURLConnection connection;
        DataOutputStream dataOutputStream;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        int bytesRead,bytesAvailable,bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File selectedFile = new File(selectedFilePath);

        String[] parts = selectedFilePath.split("/");
        final String fileName = parts[parts.length-1];

        if (!selectedFile.isFile()){
            dialog.dismiss();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvFileName.setText("Source File Doesn't Exist: " + selectedFilePath);
                }
            });
            return 0;
        }else{
            try{
                FileInputStream fileInputStream = new FileInputStream(selectedFile);
                URL url = new URL(SERVER_URL);
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);//Allow Inputs
                connection.setDoOutput(true);//Allow Outputs
                connection.setUseCaches(false);//Don't use a cached Copy
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setRequestProperty("ENCTYPE", "multipart/form-data");
                connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                connection.setRequestProperty("uploaded_file",selectedFilePath);

                //creating new dataoutputstream
                dataOutputStream = new DataOutputStream(connection.getOutputStream());

                //writing bytes to data outputstream
                dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
                dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                        + selectedFilePath + "\"" + lineEnd);

                dataOutputStream.writeBytes(lineEnd);

                //returns no. of bytes present in fileInputStream
                bytesAvailable = fileInputStream.available();
                //selecting the buffer size as minimum of available bytes or 1 MB
                bufferSize = Math.min(bytesAvailable,maxBufferSize);
                //setting the buffer as byte array of size of bufferSize
                buffer = new byte[bufferSize];

                //reads bytes from FileInputStream(from 0th index of buffer to buffersize)
                bytesRead = fileInputStream.read(buffer,0,bufferSize);

                //loop repeats till bytesRead = -1, i.e., no bytes are left to read
                while (bytesRead > 0){
                    //write the bytes read from inputstream
                    dataOutputStream.write(buffer,0,bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable,maxBufferSize);
                    bytesRead = fileInputStream.read(buffer,0,bufferSize);
                }

                dataOutputStream.writeBytes(lineEnd);
                dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                serverResponseCode = connection.getResponseCode();
                String serverResponseMessage = connection.getResponseMessage();

                Log.i(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);

                //response code of 200 indicates the server status OK
                if(serverResponseCode == 200){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvFileName.setText("File Upload completed.\n\n You can see the uploaded file here: \n\n" + "http://192.168.1.101/uploadImage/upload/"+ fileName);
                            Toast.makeText(MainActivity.this, "File Uploaded Successfully", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                //closing the input and output streams
                fileInputStream.close();
                dataOutputStream.flush();
                dataOutputStream.close();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this,"File Not Found",Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (MalformedURLException e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, "URL error!", Toast.LENGTH_SHORT).show();

            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, "Cannot Read/Write File!", Toast.LENGTH_SHORT).show();
            }
            dialog.dismiss();
            return serverResponseCode;
        }

    }
}

A:
In marshmallow 6.0.0 and above you need to use run time permissions.

This function checks permissions is granted or not?, also prompt permission that is required
public  boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
    if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            == PackageManager.PERMISSION_GRANTED) {
        Log.v(TAG,"Permission is granted");
        return true;
    } else {

        Log.v(TAG,"Permission is revoked");
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        return false;
    }
}
else { //permission is automatically granted on sdk<23 upon installation
    Log.v(TAG,"Permission is granted");
    return true;
}
}

Check Permission result callback: if permission is granted or not
    @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
        Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
        //resume tasks needing this permission
    }
    }

A: After the Android 6.0 Marshmallow google add restrict add permissions at runtime.
see that link
add that line of code to your MainActivity in on create() Method.
     private ArrayList<Integer> listPermission;// add all permission in list which you used in manifes.xml
        listPermission = new ArrayList<>();
            listPermission.add(AISPermission.WRITE_EXTERNAL_STORAGE);
            listPermission.add(AISPermission.READ_CONTACTS);
            listPermission.add(AISPermission.SEND_SMS);
            listPermission.add(AISPermission.MICROPHONE);
PermissionUtils.requestPermission(context, listPermission, new PermissionUtils.OnRequestedPermissionListListener() {
                    @Override
                    public void onPermissionListResult(ArrayList<Integer> responsePermissionList, ArrayList<Boolean> isPermissionGrantedList) {
//                        if(isPermissionGrantedList.get())
                        for (int i = 0; i < responsePermissionList.size(); i++) {
                            if (responsePermissionList.get(i) != listPermission.get(i) || !isPermissionGrantedList.get(i)) {
                                return;
                            }
                        }
                        startActivity(new Intent(context, MainActivity.class));
                    }
                });
}


text:
Q: Why isn't this function to calculate the average of an integer list not working? I'm trying to make a function which adds up all the numbers from a given list and then divides it by 6.
average :: [Integer] -> Integer
average m = (sum m) quot 6

But this is the error message I'm receiving:
Couldn't match type `Integer'
              with `(a0 -> a0 -> a0) -> a1 -> Integer'
Expected type: [(a0 -> a0 -> a0) -> a1 -> Integer]
  Actual type: [Integer]
In the first argument of `sum', namely `m'
In the expression: (sum m) quot 6

A: You need backticks around quot, or write it first
sum m `quot` 6
quot (sum m) 6

A: In Haskell we write the function name before the arguments. For quot you write:
quot 17 2

So in your case:
quot (sum m) 6

Haskell has some sytactic sugar that allows you to write functions in so called infix notation. This is what user mb14 refers to.


text:
Q: How to check HTTP Status Code of dynamically added *.js for a project I need to check the Response Code of a dynamically added JS into DOM. So Code looks basically like this one:
var newScript = document.createElement("script");
newScript.src = "http://www.example.com/dynamic-XXX.js";
target.appendChild(newScript);

The XXX will change and I am loading the File from Google Cloud Storage. So if I have a 200, everything is fine. But I need to check if I have 201 Status Code.
Any Ideas how to solve this in a nice way ?


text:
Q: TestStack White cannot setValue to OpenFileDialog's ToolStrip I want to change folder path to an OpenFileDialog.

the tool strip properties are
ToolStrip. AutomationId:1001, Name:位址: C:\Users\user\Desktop\test\理想国\Picture, ControlType:工具列, FrameworkId:Win32

I use
ToolStrip ts =  window.GetToolStrip("1001");
ts.SetValue(@"C:\");

ts I got is correct item, my program can move mouse to hover the Item but I just can't SetValue or Enter to it.
Thanks for reading my question.

A:         IUIItem a = window.Get(SearchCriteria.ByAutomationId("Item 202"));

click this button first
a.Click();

then use SendKeys.SendWait(value);
SendKeys.SendWait(paths.ElementAt(0));

Last step, KeyIn "Return"
window.KeyIn(KeyboardInput.SpecialKeys.RETURN);

Done.


text:
Q: LINQ magic for finding multiple items in a collection without researching for each one? UPDATE: the dictionary solution is great except when the number of thing being looked for pales compared to the number of things in the list.  I should have stated that up front.
Say you have the array:
var arr = {
  Tuple.Create("1", "won"),
  Tuple.Create("4", "fo"),
  Tuple.Create("3", "twee",
  Tuple.Create("2", "too")
  // ...
  // ...and many more entires...
};

And you are told to find the strings "1" and "2", so you do this:
string s1 = arr.First(c => c.Item1 == "1").Item2;
string s2 = arr.First(c => c.Item2 == "2").Item2;

But in review, it is noted that you searched the same array twice so you change it to:
string s1;
string s2;
bool founds1 = false;
bool founds2 = false;
foreach(int i; i < arr.Length; i++)
{
  if(arr[i] == "1")
  {
    s1 = arr[i].Item2;
    founds1 = true;
  }
  if(arr[i] == "2")
  {
    s2 = arr[i].Item2
    founds2 = true;
  }
  if(founds1 && founds2)
    break;
}

Is there any LINQ way of achieving the same result without being subject to efficiency problems?

A: If you want to be able to look up items based on the first part of the Tuple, you're using the wrong data structure.
Switch to using a Dictionary<string, string> and you can use the indexer without having to enumerate the entire collection:
var dict = new Dictionary<string, string>
{
    { "1", "won" },
    { "4", "fo" },
    { "3", "twee" },
    { "2", "too" }
};

if(dict.ContainsKey("1"))
{
    founds1 = true;
    s1 = dict["1"];
}

// And so on...

A: To efficiently search through a collection of key-value pairs you should put them into a dictionary, rather than an array:
var lookup = arr.ToDictionary(pair => pair.Item1, pair => pair.Item2);

This allows you to search for either value extremely quickly:
var s1 = lookup["1"];
var s2 = lookup["2"];

If you are only ever searching for a very small number of items, and don't have a particularly large data set, then you may be better of just doing multiple linear searches, but as the number of searches you're doing rises, the more you have to gain from spending the time up front to create the lookup.
Also note that of the two solutions you provided, they will have virtually equal performance implications.  Doing one loop that takes twice as long as two other loops results in the same amount of work.  The only real reason to use your second solution is if the sequence that you have cannot reliably be enumerated multiple times (perhaps it represents a database query, causes side effects, doesn't yield the same values on each iteration, etc.).


text:
Q: Multiple errors when using gl I'm trying to create a Snake game with C++ using Opengl, SDL and GL although I have everything Linked correctly I get a pile of errors when building, I have looked around and found that these errors are pretty common when using GL although  I can't seem to pinpoint why I'm getting them as I've taken the precautions like including "windows.h" before including "GL/freeglut.h" can anyone help?
Errors included are:
error C2144: syntax error : 'void' should be preceded by ';'
Error   C2144   syntax error: 'void' should be preceded by ';'  OpenGLTutorial  c:\program files (x86)\windows kits\8.1\include\um\gl\gl.h  1157
Error   C4430   missing type specifier - int assumed. Note: C++ does not support default-int    OpenGLTutorial  c:\program files (x86)\windows kits\8.1\include\um\gl\gl.h  1157
Error   C2182   'APIENTRY': illegal use of type 'void'  OpenGLTutorial  c:\program files (x86)\windows kits\8.1\include\um\gl\gl.h  1157
Error   C2146   syntax error: missing ';' before identifier 'glAccum'   OpenGLTutorial  c:\program files (x86)\windows kits\8.1\include\um\gl\gl.h  1157
Error   C2144   syntax error: 'void' should be preceded by ';'  OpenGLTutorial  c:\program files (x86)\windows kits\8.1\include\um\gl\gl.h  1157
Error   C4430   missing type specifier - int assumed. Note: C++ does not support default-int    OpenGLTutorial  c:\program files (x86)\windows kits\8.1\include\um\gl\gl.h  1157
Error   C2182   'APIENTRY': illegal use of type 'void'  OpenGLTutorial  c:\program files (x86)\windows kits\8.1\include\um\gl\gl.h  1157
Error   C2146   syntax error: missing ';' before identifier 'glAccum'   OpenGLTutorial  c:\program files (x86)\windows kits\8.1\include\um\gl\gl.h  1157

Main cpp
#ifdef __MINGW32__
#include <windows.h>
#endif

#ifdef WIN32
#include <windows.h>
#endif

#include <GL/freeglut.h>
#include <SDL2/SDL.h>
#include <time.h>
#include "SnakeGame.hpp"

int main(void) {

    srand(time(NULL));

    SnakeGame *f = new SnakeGame();
    f->run();
    return 0;
}

Arena.hpp
#ifdef _WIN32
#include <windows.h>
#endif

#include <GL/freeglut.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

#include "Obstacle.hpp"
#include "Fruit.hpp"
#include "Snake.hpp"
#include "Font.hpp"

class Arena {

 public:

  Arena(void);
  virtual ~Arena(void);
  void update(void);
  inline void draw(void);
  Snake *snake;

 private:
  float rot;
  unsigned int score;
  Font *font;
  inline void correct_elements(void);
  void drawRainbowTriangle(void);
  void correct_fruit(void);
  void correct_obstacle(void);
  void correct_snake(void);
  bool is_snake_dead(void);
  bool is_snake_eating(void);
  Obstacle *obstacle;
  Fruit *fruit;
};

Element.hpp
#include <iostream>
#include <ostream>
#include <GL/freeglut.h>
#include <GL/gl.h>

class Element {

public:
  Element();
  virtual void draw() = 0;
  int getX();
  int getY();
  void setX(int it);
  void setY(int it);
  void display();

protected:
  int x;
  int y;
};

Font.hpp
#include <GL/freeglut.h>
#include <string.h>

class Font {

public:
  void bitmap_output(int x, int y, const char *string, void *font = GLUT_BITMAP_TIMES_ROMAN_24);

private:

};

Fruit.hpp
#include <GL/freeglut.h>
#include <GL/gl.h>

#include "Element.hpp"

class Fruit : public Element {

public:
  void draw();
};

Game.hpp
include <SDL2/SDL.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/freeglut.h>

class Game {

 public:
  Game();
  ~Game();
  virtual void run()=0;
  int get_score();
  void set_score(int s);
  bool paused;
 private:

 protected:
  SDL_Renderer* displayRenderer;
  SDL_Window* displayWindow;
  SDL_RendererInfo displayRendererInfo;
};

Snake.hpp
#include <iostream>
#include <list>
#include <GL/gl.h>
#include <GL/freeglut.h>
#include "Element.hpp"

enum Dir {UP, DOWN, RIGHT, LEFT};

class Body : public Element {

public:
  void draw() {
    glColor3ub(0, 0, 255);
    glPushMatrix();
    glTranslatef(x, y, -y);
    glutSolidCube(1);
    glPopMatrix();
  }
};

class Snake {

public:
  Snake();
  ~Snake();
  void update(void);
  void draw(void);
  void grow(int size);
  void setDir(Dir direction);
  std::list<Body> body;
  std::list<Body>::iterator iter;

private:
  Dir dir;
};

Snake game.hpp
#ifdef _WIN32
#include <windows.h>
#endif

#include <stdlib.h>
#include <SDL2/SDL.h>
#include <GL/glu.h>
#include <GL/gl.h>
#include "Arena.hpp"
#include "Game.hpp"

class SnakeGame : public Game {

 public:
  SnakeGame();
  virtual ~SnakeGame();
  void run();

 private:
  bool is; //is the game running

  Arena arena;
  void keyboard(const SDL_Event &event);
};

A: You're testing for the wrong preprocessor macro. Make it read like this
#ifdef _WIN32
#include <windows.h>
#endif

note the underscore in _WIN32. No need to test for _MINGW32_, as the other macro is defined there as well.


text:
Q: Help with updating record from marketing cloud to sales cloud Is there a way to update the sales cloud record from marketing cloud to sales cloud ?
So , I have a multiselect pick list in sales cloud contact object.
I am using Sync DE to get all the data and with the help of query my standard DE will get update.
Then, I created a journey builder (This is basically for engagement split) and i add email wait activity and engagement split.
I also select Update Contact record .
Now ,Lets say i have 3 value in contact object as a multiselect picklist.
 and once my journey will start so it will update my sales cloud data.
Can anyone suggest me the best approach to do this ?

A: Since you already have a connector setup between your marketing cloud and sales cloud, I'd recommend using the Sales and Service Cloud Activities which is available within the Journey Builder.
Basically, you'd need to choose the right object where you'd want the update to be made, in your case it would be Contact Activity. Drag that activity to the point in the journey where you'd like the action to happen and within contact activity, you can:

*

*Create a CRM contact record when a Marketing Cloud contact reaches the activity.

*Update a CRM contact record with Marketing Cloud contact data.

This is possibly the best and easiest way to update back to Sales or Service Cloud since it doesn't require any complex script writing and has an interactive user-friendly interface.
Update:
If you have a picklist within the Contact object then you'd be able to get the same picklist during the contact activity setup in journey builder.

Reference:

*

*Sales and Service Cloud Activities
Screenshot Reference:


text:
Q: how to get only Customer data who is logged in template profile.html but showing all Customer in django models.py ( considering all required data )  how to get only logged in customer but it is showing all Customer
class Customer(models.Model):

first_name = models.CharField(max_length=50)
last_name = models.TextField(max_length=50)
phone = models.CharField(max_length=15)
email = models.EmailField(max_length=100 ,default='')
password = models.CharField(max_length=500)

views.py ( considering all required done )
def profile(request):

data= Customer.objects.all()
return render(request,'profile.html' ,{'data':data})

profile.html ( considering making urls) and all doing requirement
{% if data %}
{% for d in data %}

{{ d.email }}

{% endfor %}
{% endif %}

A: data= Customer.objects.all()
data is a list of Customers not a single Customer, so there is no email attribute available. Calling data.email in the template returns None.
You need to loop through data in the template.
{% if data %}
{% for d in data %}

{{ d.email }}

{% endfor %}
{% endif %}


text:
Q: cannot assign a value to a variable in Backing Bean in JSF I'm using JSF and making a webapp. I succeeded to assign a value to a variable in normal xhtml page, but not in a page where i have a datatable of primefaces. Biding doesnt work so search has to be null.
Here is my code.

            <f:facet name="header">

                    <h:outputText value="地域で検索" />

                    <h:commandLink type="submit" value="地域で検索" action="#{bb.filterTable}" class="Button"/>

            </f:facet>

//left out

search is null in this method.
public String filterTable() {
    System.out.println("filterTable()");
    System.out.println("search in filterTable() = " + search);
    Flash flash = FacesContext.getCurrentInstance()
            .getExternalContext().getFlash();
    flash.put("search", search);
    System.out.println("search in filterTable in Bb = " + search);
    return "filtered-table.xhtml";
}

Thank you in advance.


text:
Q: If two columns match, return only closest absolute value from other two columns I have a shapefile with points that are joined to the closest twenty points from another shapefile. The joined shapefile has columns from the original shapefile: name (ID), elevation (Z), name from joined shapefile (name) and elevation from the joined shapefile (Z2).
So twenty rows have the same ID and name but differing Z and Z2. I would like to use the field calculator to return the row that has the smallest absolute difference between Z and Z2 with the matching ID and name.
Using a case statement in the qgis field calculator I can get all the results to return the difference in a new column:
CASE WHEN "Name" = "ID" THEN abs("Z" - "Z2") END

but I would like only the smallest value to return.

A: If you would like to return the smallest absolute value, you can take the minimum of each Name group by using the minimum function like so:
case when "Name" = "L1_ID" then minimum(abs("L1_Elev" - "Elev2"), "Name") end


text:
Q: Why isn't std::function template constructor using universal reference? I think that constructor with universal reference parameter has better performance than the one without reference.
From cppreference (https://en.cppreference.com/w/cpp/utility/functional/function/function), we can see that the template constructor for std::function is not using reference.
template< class F > function( F f );

Is it a mistake? If not, why the standard doesn't requires the constructor use universal reference?
EDIT:
Let's think about two cases.

*

*F is a built-in type, here a function pointer whose size is 4 bytes.

Using universal reference:
lvalue case: 4 bytes are copied.
rvalue case: 4 bytes are copied. (Will you apply a std::move to built-in type?)
Passing by value:
all cases: 4 bytes are copied.

*F is a type with non-trivial copy constructor, ex. a lambda type which captures a std::string by value. This example stands for most cases, do you agree?

Using universal reference:
lvalue case: copy constructor is invoked once
rvalue case: move constructor is invoked once
Passing by value:
lvalue case: a move and a copy
rvalue case: a move
Is this classification complete? If so, we can run into the conclusion that universal reference is no worse then passing by value. Then it returns to the original question.
EDIT again:
Maybe lambdas without captures are the most common cases, where passing by value is actually passing nothing while passing by reference is passing a pointer. This may be the key. LWG 2774 is related to this question. See it in comments.

A: Because that constructor moves its argument, accepting a reference is pointless. This comes down to the usual advice on when to take values.
If you pass a primitive, like an int, passing by reference is a pessimisation. If you pass a complex type, like a std::string, you can already std::move it into the argument (and, if you don't, then that's because you wanted a copy anyway). You get the best of both worlds.
// Bog-standard choice between value and ref; original value only observed

void foo(const int& x) { cout << x << '\n'; }
void foo(const int x) { cout << x << '\n'; }  // Better!

void foo(const std::string& x) { cout << x << '\n'; }  // Better!
void foo(const std::string x) { cout << x << '\n'; }

// When we want to store

void storeACopy(int);
void foo(const int& x) { storeACopy(x); }
void foo(const int x) { storeACopy(x); }  // Better!

void storeACopy(std::string);
void foo(const std::string& x) { storeACopy(x); }  // Meh
void foo(std::string x) { storeACopy(std::move(x)); }  // Cheap!

// So, best of both worlds:
template <typename T>
void foo(T x) { storeACopy(std::move(x)); }

// This performs a copy when needed, but allows callsite to
// move instead (i.e. total flexibility) *and* doesn't require silly
// refs-to-primitives

It also signals to the call site that the original object will not be modified unless you specifically yield ownership with std::move.
If instead the function took a reference, okay you'd potentially save one move if you want to yield. But, moves are supposed to be super-cheap so we're not concerned about that. And if you didn't want to yield then suddenly you have to go through the rigmaroll of an object copy at the callsite. Ugh!
This pattern is key to making the most out of move semantics.

A:
I think that constructor with universal reference parameter has better performance than the one without reference.

Why do you think that? Have you measured? What if we're talking about passing int? Reference (universal / forwarding or not) is not always a boost for performance.

Is it a mistake?

No, it's the standard convention to pass function objects by value. They are meant to be cheap to copy and when implementing own function objects, you should keep that in mind.

If not, why the standard doesn't requires the constructor use universal reference?

Ultimately, why would it? :)


text:
Q: How to enable CORS with AWS SAM I'm trying to enable CORS in my AWS SAM app. Here is the snippet from my template.yaml:
Globals:
  Api:
    Cors:
      AllowMethods: "'*'"
      AllowHeaders: "'*'"
      AllowOrigin: "'*'"

Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: prod
      Auth:
        Authorizers:
          MyCognitoAuthorizer: ...

  getByIdFunc:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handler.handle
      Events:
        ApiEvent:
          Type: Api
          Properties:
            Path: /{id}
            Method: GET
            RestApiId: !Ref MyApi

According to this Using CORS with AWS SAM and that https://github.com/aws/serverless-application-model/issues/373, the cors config should work but unfortunately no header is set on the API response, as seen below.
< HTTP/2 200
< content-type: application/json
< content-length: 770
< date: Tue, 13 Apr 2021 19:55:31 GMT
< x-amzn-requestid: ...
< x-amz-apigw-id: ...
< x-amzn-trace-id: Root=1-...-...;Sampled=0
< x-cache: Miss from cloudfront
< via: 1.1 ...cloudfront.net (CloudFront)
< x-amz-cf-pop: FRA2-C2
< x-amz-cf-id: ...==
<
* Connection #0 to host ....execute-api.eu-central-1.amazonaws.com left intact
[{"model": ..}]

I also tried adding the cors config to the API definition (MyApi) itself like its stated in the offical docs here, but without success.
I could add the header in the response by myself but i rather have it in the template file.

A: What solved it for me was adding the following to my template.yaml:
Globals:
    Api:
        Cors:
            AllowMethods: "'GET,POST,OPTIONS'"
            AllowHeaders: "'content-type'"
            AllowOrigin: "'*'"
            # AllowCredentials: true  Uncomment only if you choose a specific origin instead of the * wildcard.

And just like nirvana124 and Nitesh said, you also need to return these headers with the response in each endpoint:
return {
    statusCode: 200,
    headers: {
        "Access-Control-Allow-Headers" : "Content-Type",
        "Access-Control-Allow-Origin": "*", // Allow from anywhere
        "Access-Control-Allow-Methods": "GET" // Allow only GET request
    },
    body: JSON.stringify(response)
}

A: Using SAM/CLoudformation or AWS Console you can setup CORS headers for OPTIONS method which will be called by browser before calling your actual API method(GE/POST etc). From postman or any other service only your endpoint will be called.
When we are using lambda proxy with API Gateway we need to set the CORS headers in the response object from lambda.

To enable CORS for the Lambda proxy integration, you must add Access-Control-Allow-Origin:domain-name to the output headers. domain-name can be * for any domain name.

return {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Headers" : "Content-Type",
            "Access-Control-Allow-Origin": "*", // Allow from anywhere
            "Access-Control-Allow-Methods": "GET" // Allow only GET request
        },
        body: JSON.stringify(response)
    }

A: With your script, CORS is enabled on API Gateway, but SAM always creates PROXY integration from the API Gateway to Lambda, which means that API Gateway cannot add any integration response and it will pass the response which it will receive from LAMBDA. That's why you need to handle the CORS header inside your lambda rather than depending on API Gateway. Below is the sample code to return from the LAMBDA along with the response.
return {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Headers" : "Content-Type,X-Amz-Date,Authorization,X-Api-Key,x-requested-with",
            "Access-Control-Allow-Origin": "*", // Allow from anywhere
            "Access-Control-Allow-Methods": "OPTIONS,POST,GET,PUT,DELETE,PATCH" // Allow only GET request
        },
        body: JSON.stringify(response)
    }

A: For anyone using API Gateway Version 2 (HttpApi), it doesn't have support for 'AddDefaultAuthorizerToCorsPreflight', at least not specified in their documentation.
Instead (per AWS guidelines), we need to add a route in lambda function for OPTIONS /{proxy+} and turn off Authentication for this route.
MyHttpApi:
 Type: AWS::Serverless::HttpApi
 Properties:
  Auth:
    DefaultAuthorizer: OAuth2
    Authorizers:
      OAuth2:
        JwtConfiguration:
          issuer: "..."
          audience:
            - ...
        IdentitySource: "$request.header.Authorization"
  CorsConfiguration:
    AllowOrigins:
      - "*"
    AllowMethods:
      - GET
      - POST
      - OPTIONS
    AllowHeaders:
      - Content-Type
      - Accept
      - Access-Control-Allow-Headers
      - Access-Control-Request-Method
      - Access-Control-Request-Headers
      - Authorization
MyLambdaFunction:
 Type: AWS::Serverless::Function
 Properties:
  Handler: index.handler
  Events:
    CorsPreflightEvent:
      Type: HttpApi
      Properties:
        Path: /{proxy+}
        Method: OPTIONS
        Auth:
          Authorizer: NONE
        ApiId: !Ref MyHttpApi

A: Late to the party, but for anyone else from Google: add this to the Auth section, this won't allow Authorizer to process CORS HTTP headers
Api:
  Auth:
    AddDefaultAuthorizerToCorsPreflight: false


text:
Q: Eigenvalue response to perturbation Let's say I have a diagonalizable  $3\times3$ matrix $$ \begin{pmatrix} a & b & c \\ d & e & f \\ g & h & i \end{pmatrix}$$
with 3 distinct eigenvalues $\lambda_1, \lambda_2, \lambda_3$. Let's say I now add a small perturbation to $i$ of the form $-k^2$ so that the matrix becomes:
$$ \begin{pmatrix} a & b & c \\ d & e & f \\ g & h & i - k^2 \end{pmatrix}$$
Is there are formula for how the eigenvalues will change? I'm not even sure where to start.

A: Write $A = \begin{bmatrix}a & b & c \\ d & e & f \\ g& h & i\end{bmatrix}.$
Say that $A$ is Hermitian that is $A = \overline{A}^T$ then you could use Weyl's perturbation theorem which says that if $B$ is another Hermitian matrix then
$$\max_{1\leq i \leq 3}|\lambda_i(A+B)-\lambda_i(A)|\leq \|B\|$$
Here $\lambda_i$ is the map which takes Hermitian matrices to their eigenvalues ordered non-increasingly.
In your case
$$B = \begin{bmatrix}0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & k^2\end{bmatrix}$$


text:
Q: How to capture CSS element using Selenium VBA? I am writing code in VBA using Selenium to extract information from eCommerce platforms.
I want to capture for a particular product, information like # Sizes, sizes which are available and which are stocked out.
I am able to get the # sizes and their names but not information like stock outs.
Source Code -->

      L

      XL

VBA Code-->
'''
Set results = driver.FindElementsByCSS("circle-size variant oos")
For Each result In results
    Worksheets("Sheet1").Cells(1, 40 + c).Value = results.Text
    c = c + 1
Next
'''

A: driver.FindElementsByCSS("circle-size variant oos")

to make this Css work, you should remove the spaces and put a .
driver.FindElementsByCSS("div.circle-size.variant oos")

should get the job done.


text:
Q: Java "self" (static) reference I am looking for a "self" reference to the current class in JAVA in a static context manner like in PHP Scope Resolution Operator?
Solution: Break out of scope? BEWARE, this is compared to a static definition really slow (by factor 300):
static Logger LOG = LoggerFactory.getLogger(new RuntimeException().getStackTrace()[0].getClassName());

The old-fashioned way would be:
static Logger LOG = LoggerFactory.getLogger(<Classname>.class.getName());

Are there any alternatives? I'm looking for a way to put the logger definition in an abstract class. The logger should determine the class it's being called from by itself.

A: You should not inherit logger. Just declare logger in each class.
But if you don't want do such useful think, just don't make it static)

A: The slightly faster
static final Logger LOG = LoggerFactory.getLogger(
       Thread.currentThread().getStackTrace()[0].getClassName());

If you do this 1000 times it will take 36 ms using Class.class.getName() and 60 ms doing it this way.  Perhaps its not worth worrying about too much. ;)

A: I don't think there are any alternatives that are significantly different to the two in your question.
You could create a helper method like this:
public static String getCallingClassname() {
    return new RuntimeException().getStackTrace()[1].getClassName();
}

and then
static Logger LOG = LoggerFactory.getLogger(Helper.getCallingClassname());

but that's as expensive as the original version.  (FWIW - 300 times as slow is probably not a major concern, unless you have thousands of these loggers.  Each of these statics is initialized just once ...)
My personal preference is for the "old fashioned" way of doing it.

A: You don't need to use any of those. What I find convenient to use is:
   //Logger
private static final Logger logger = LoggerFactory.getLogger(CreateEmployeeRecord.class or this.class);
Do it in every class that needs logging, and change class name in bracket to corresponding class wherever it's being used.


text:
Q: Can an open set contain its supremum? I say the answer is no:
By definition,let $A \subset \mathbb{R} $ and let $s$ be an upperbound for $A$. Then, $s=sup A$ if and only if, $\forall \epsilon>0$, $\exists a \in A$ satisfying $s-\epsilon < a$
With this in mind, and I'm having trouble stating it formally, let's assume that $A \subset \mathbb{R}$ is open, as the question states. For a contradiction, let's say that $s \in A$. Let $b$ be an upperbound for $A$. Since $s = sup A$, for an arbitrary $\epsilon$, $s + \epsilon \leq b$, but $b \notin A$.
Where I am going with this is that $V_\epsilon (s)$ is not  contained in $A$, which contradicts the fact that $A$ is an open set.
How is my logic and how can I improve on that?
Thanks!

A: In the reals, using the Euclidean topology, you are right and your argument works. I would phrase it as:

Let $s$ be an upper bound for $A$. Then for some $\epsilon$, there is a ball $B_{\epsilon}(s)$ around $s$ contained in $A$, since $A$ is open. But in particular, $s+\frac{\epsilon}{2}$ lies in $A$, contradicting that $s$ is an upper bound.

If you are averse to contradiction, you can do it directly: for every $s \in A$, there is $s+\epsilon/2 \in A$ with $s+\epsilon/2 > s$.

In a general partially ordered topological space, though, open sets may contain their suprema: in $[0,1]$ with the subspace Euclidean topology, $[0,1]$ is open and contains its sup, $1$.


text:
Q: How to compare columns from two different Data Frames and keep the values from the first Data Frame? I have two dataframes of different sizes. They both have four columns: Words, x, y and z.
However, when joining these two dataframes, I want to keep the values of x, y, z of the words that are similar. The words that doesn't exist in df1 but exist in df2 are kept.
I tried to use pd.merge but this will keep the two values and only similar words. And if I use pd.concat I have to drop similar elements, but will not be from the first data frame.
Sample
df1 = pd.DataFrame({'Words':
       ['aardvark', 'abalone', 'abandon'],
     'x': [0.999, 0.888, 0.777],
     'y': [0.999, 0.888, 0.777],
     'z': [0.999, 0.888, 0.777]})

df2 = pd.DataFrame({'Words':
       ['aaaaahh', 'aardvark', 'abalone', 'abandon', 'zoo', 'zoom', 'zucchini'],
     'x': [0.199, 0.111, 0.222, 0.333, 0.232, 0.842, 0.945],
     'y': [0.929, 0.111, 0.222, 0.333, 0.112, 0.62, 0.265],
     'z': [0.993, 0.111, 0.222, 0.333, 0.212, 0.344, 0.745]})

# Expected output
df_res = pd.DataFrame({'Words':
          ['aaaaahh', 'aardvark', 'abalone', 'abandon', 'zoo', 'zoom', 'zucchini'],
     'x': [0.199, 0.999, 0.888, 0.777, 0.232, 0.842, 0.945],
     'y': [0.929, 0.999, 0.888, 0.777, 0.112, 0.62, 0.265],
     'z': [0.993, 0.999, 0.888, 0.777, 0.212, 0.344, 0.745]})

What I tried
import pandas as pd

# Merge
df_res = pd.merge(df1, df2, on='Word', how='inner')

# Concat
df_concat = pd.concat(objs=[df1, df2], ignore_index=True)
df_concat = pd.drop_duplicates(subset=['Word'], keep=False, ignore_index=True)

# Compare
d_res = d1[(d1['Word'] != d1['Word'])]
ValueError: Can only compare identically-labeled Series objects

A: You can use df.append to append df1 to df2, followed by drop_duplicates, with keep='last', then sort_index and reset_index:
>>> (df2.append(df1)
        .drop_duplicates('Words', keep='last')
        .sort_index()
        .reset_index(drop=True))

      Words      x      y      z
0   aaaaahh  0.199  0.929  0.993
1  aardvark  0.999  0.999  0.999
2   abalone  0.888  0.888  0.888
3   abandon  0.777  0.777  0.777
4       zoo  0.232  0.112  0.212
5      zoom  0.842  0.620  0.344
6  zucchini  0.945  0.265  0.745

A: Maybe less performant than @Sayandip Dutta answer, you could try a right join (or left, depending on the order you put arguments in pd.merge):
In [4]: res = pd.merge(df1, df2, how='right', on='Words', suffixes=("_1", "_2"))

In [5]: res
Out[6]:
      Words    x_1    y_1    z_1    x_2    y_2    z_2
0  aardvark  0.999  0.999  0.999  0.111  0.111  0.111
1   abalone  0.888  0.888  0.888  0.222  0.222  0.222
2   abandon  0.777  0.777  0.777  0.333  0.333  0.333
3   aaaaahh    NaN    NaN    NaN  0.199  0.929  0.993
4       zoo    NaN    NaN    NaN  0.232  0.112  0.212
5      zoom    NaN    NaN    NaN  0.842  0.620  0.344
6  zucchini    NaN    NaN    NaN  0.945  0.265  0.745

Then you can fillna of x_1, y_1, z_1 with values of x_2, y_2 and z_2.
In [8]: res.x_1.fillna(res.x_2, inplace=True)

In [8]: res.y_1.fillna(res.y_2, inplace=True)

In [9]: res.z_1.fillna(res.z_2, inplace=True)

In [10]: df_res = res[["Words", "x_1", "y_1", ,"z_1"]]

In [11]: df_res
Out[11]:
      Words    x_1    y_1    z_1
0  aardvark  0.999  0.999  0.999
1   abalone  0.888  0.888  0.888
2   abandon  0.777  0.777  0.777
3   aaaaahh  0.199  0.929  0.993
4       zoo  0.232  0.112  0.212
5      zoom  0.842  0.620  0.344
6  zucchini  0.945  0.265  0.745


text:
Q: Swap between UISplitViewController allowed? I have a need for two UISplitViewController in my app and i am switching back and forth between them using rootViewController swap. Are there any risks in getting the app approved ?
thanks

A: All rules that are used during app review are described in App Store Review Guidelines.
Point 10. User interface has such rules:

10.1 Apps must comply with all terms and conditions explained in the Apple iOS Human Interface Guidelines.
  10.3 Apps that do not use system provided items, such as buttons and icons, correctly and as described in the Apple iOS Human Interface Guidelines may be rejected.

iOS Human Interface Guidelines have such rules for Split View Controllers:

*

*Avoid creating a secondary pane that is narrower than the primary pane.

*Avoid displaying a navigation bar in both panes at the same time.

*In general, indicate the current selection in the primary pane in a persistent way.

*Give people alternative ways to access the primary pane, if appropriate.

As you see it says nothing about switching between different objects of UISplitViewController. You will be good as you are not trying to display both split controllers at the same time.


text:
Q: How do I encapsulate third-party JavaScript files so they don't pollute the global scope? One of my clients is asking if they can add some JavaScript to track user behavior to their website. At first glance I fear that it is going to interfere with other third-party analytics scripts on the site because it looks like both parties have used the same JavaScript compressor. I don't want to comb through and search for every possible naming collision so . . .
Is there a way I can include third-party scripts (script files which live on a separate domain) but wrap them in their own namespace or give them their own scope so they don't collide with other globally declared variables and functions?

A: In order of isolation:

*

*An (i)frame hosted on a different domain - no direct interactions possible

*An (i)frame hosted on the same domain - interactions only possible via explicit window/frame references

*A self-executing anonymous function - interactions are simple but well-behaved code can be isolated

*None - hope no one uses the same variable or function names

It would depend on the third-party script but I generally lean towards #2.  Interactions are possible but you're insulated from casual document.write use and global namespace pollution.
Edit: Example of #2
in page.html

...Your content...

tracker.html (optionally the whole thing)

That's the basic structure but needs a little more setup or else all traffic would appear to be coming from tracker.html.  For a tracking script I suggest providing the top (real) page's path in the query string to the iframe: "tracker.html?u=thispage.html".  You could setup the query string either server side or via javascript:
page.html (again)

...Your content...

You could optionally just use location.pathname rather than location.href (which has protocol, domain, etc.) if the path is enough for your tracking.
After all that... if the tracking script is from a reputable source (StatCounter, Google Analytics, etc.) I suggest trusting them to not step on your pages variables and functions.  Options 1 and 2 are really for low trust situations.

A: Like this:
(function() {
    // insert code here
})();

Enjoy ;)

A: It should not be a problem. Javascript compressors do not rename global variables (for obvious reasons), and any well-designed script will not expose many (any) globals. If they want you to deploy it on your page, it is their responsibility to prevent clashes.

A: It depends of what you want to do exactly.
1) You want to load the third party scripts in your pages in a way that your sure it wont break your scripts.
You can't do a lot here.
Ask the third party to do clean scripts.... not really possible in general
Load the script in an iframe.... probably will make the script useless
There's maybe a way, but it's probably stupid :
load the script via ajax (may need a proxy to avoid cross domain), create a JS function with the content of the script (new Function('The content of the script');), and then execute the function (you can also use eval... it's the same).
This way, you can manage arguments you give to the function, and this way you can protect global variables for example.
Doing this is probably a good way to break the third party script. Will it protect yours ?... maybe.
Anyway, you should also protect you from third party script unavailable. Whenever you try to use a variable declared in a third party script, always check if the variable is defined to be sure the script is loaded.
2) You want to code your scripts a way it won't be broken by any third party scripts
First : global variables are dangerous.
You don't know who made them, you don't know who modified them... don't trust them.
There's one variable you can trust : the this keyword in the global scope. It should be the window object, and this object should be protected a little (should be a constant at least).
If you have to create arrays, strings, regExp... try not to use the "new Something()" way to do it
var myArray = []; // not new Array();
var myRegExp = /^myRegExp$/; // not new RegExp('^myRegExp$');
var myString = 'myString'; // not new String('myString');

For example, the Array variable can be overwritten. If you use [], you won't mind.
There's cases where you can't do another way of course, but try not to.
As you can't trust global variables, you should also avoid create some. Create only the absolutely necessary global variables. everything else should be local. If your script are less intrusives, other will maybe try to do the same.
To do this (use mainly local variables), you should work in a "protected area". a good way to do this is an anonymous self-executing function.
(function () {
    // Your code here
}());

You can also pass global variables to this "base function". This can be good for minification, and for protection. You can also get an "undefined" variable to be the reference to check if variables are defined or not.
(function (window, alert, Array, undef) {
    // Your code here
    alert('I\'m safe here.');

    if([] instanceof Array) {
        alert('I\'ve got the real Array object');
    }

    if(window.jQuery === undef) {
        alert('jQuery not loaded');
    }

}(this, this.alert, this.Array));

I think this way your script should be a little bit protected. There's probably other things I forgot, but this is a good start.


text:
Q: Can one delete a function returning an incomplete type in C++? In the following example function f() returning incomplete type A is marked as deleted:
struct A;
A f() = delete;

It is accepted by GCC, but not in Clang, which complains:
error: incomplete result type 'A' in function definition

Demo: https://gcc.godbolt.org/z/937PEz1h3
Which compiler is right here according to the standard?

A: Clang is wrong.

[dcl.fct.def.general]
2 The type of a parameter or the return type for a function definition shall not be a (possibly cv-qualified) class type that is incomplete or abstract within the function body unless the function is deleted ([dcl.fct.def.delete]).

That's pretty clear I think. A deleted definition allows for an incomplete class type. It's not like the function can actually be called in a well-formed program, or the body is actually using the incomplete type in some way. The function is a placeholder to signify an invalid result to overload resolution.
Granted, the parameter types are more interesting in the case of actual overload resolution (and the return type can be anything), but there is no reason to restrict the return type into being complete here either.

A: At the beginning, 9.3.4.6 [dcl.fct] paragraph 9 required that

The type of a parameter or the return type for a function definition
shall not be an incomplete class type (possibly cv-qualified) unless
the function definition is nested within the member-specification for
that class (including definitions in nested classes defined within the
class).

A defect report was raised, and a subsequent resolution proposed and applied retrospectively (emphasis mine):

Types shall not be defined in return or parameter types. The type of a
parameter or the return type for a function definition shall not be an
incomplete class type (possibly cv-qualified) unless the function is
deleted (9.5.3 [dcl.fct.def.delete]) or the definition is nested
within the member-specification for that class (including definitions
in nested classes defined within the class).

Therefore, Clang is wrong.


text:
Q: Best way to implement users location that allows me to see what users live roughly in the same area A key part of my current project is users having the ability to see what other users live near to them. What is the best way to implement this?
I would just ask for country, state and city but because this will be international I can't have a fixed drop down list of states/administrative regions for each country, so if users spell the name of their state differently this will hinder my ability to detect that users live in the same state.
Say for example we have an the Swiss canton "St. Gallen". Some user will spell that as "Saint Gallen", others as "St Gallen" and so on. Which is obviously problematic.
Could I just ask for the zip code and use that? I've found some zipcode tools online but I'm suspecting they don't work very well. Has anyone used them?
Thanks for your asnwers.

A: Shouldn't you base your query on geographical data rather than administration one? I mean instead of comparing cities/zip codes just find people within, let's say, 5 km from current user location. And if you let every user to choose his/her location on the map, this will be as simple as choosing it from a series of drop-down lists or entering a ZIP code. Also there is an emerging geolocation HTML feature.
Querying such an information is different story thou. You'll probably gonna have to use GIS capabilities of your database: MySQL, PostgreSQL, Oracle and others.


text:
Q: Can someone resend a digitally signed email If someone receives a copy of a digitally signed email, is there any way they can resend from their own account so that it still appears to be digitally signed by the original sender.  i.e. if they resend an exact binary copy of the email will that appear to be signed?

A: Yes. Since it still was digitally signed by the original sender, it will still appear to be signed by the original sender. It works the same way with physical signatures -- I can take a letter signed by someone else and mail it to you. The letter will still appear to be signed by the same person. I just can't tamper with the contents of the letter.
If this was not so, how could servers deliver the signed email to you? All they receive is a copy of the digitally signed email. And it's not like they have some account of their own that they can send them from. The resend an exact digital copy, and of course it still appears to be signed since it still is signed since digital copies are not distinguishable from originals.

... resend from their own account so that it still appears to be digitally signed by the original sender ...

Note that since the email will, as you said, still appear to have been signed by the original sender, and it was in fact signed by the original sender, there's no vulnerability or issue here.


text:
Q: In C#, how do I save a webpage to file without destroying whatever the encoding is? Here's what I got so far (that doesn't work). At this point I thought my target was Ansi encoded, but I really don't want to have to know at this point. My browser seems to be able to determine what encoding to use, How can I?
static void GetUrl(Uri uri, string localFileName)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    HttpWebResponse response;

    response = (HttpWebResponse)request.GetResponse();

    // Save the stream to file
    Stream responseStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(responseStream, Encoding.Default);
    Stream fileStream = File.OpenWrite(localFileName);
    using (StreamWriter sw = new StreamWriter(fileStream, Encoding.Default))
    {
        sw.Write(reader.ReadToEnd());
        sw.Flush();
        sw.Close();
     }
}

After answers (currently only tested on a UTF-8 site):
static void GetUrl(Uri uri, string localFileName)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    try
    {
        // Hope GetEncoding() knows how to parse the CharacterSet
        Encoding encoding = Encoding.GetEncoding(response.CharacterSet);
        StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
        using (StreamWriter sw = new StreamWriter(localFileName, false, encoding))
        {
            sw.Write(reader.ReadToEnd());
            sw.Flush();
            sw.Close();
        }
    }
    finally
    {
        response.Close();
    }
}

A: There are three ways how web-browsers try to detect character encoding.
Look for (if it's HTML):
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">

or (for XHTML)
<?xml version="1.0" encoding="ISO-8859-1"?>

or sometimes it's even specified in http header
Content-Type: text/html; charset=ISO-8859-1

A: You should be looking for the encoding the server sends the response in. Encoding.Default does not cut the mustard here. :-)
Stream responseStream = response.GetResponseStream();
Encoding enc = Encoding.GetEncoding(response.CharacterSet);
StreamReader reader = new StreamReader(responseStream, enc);
Stream fileStream = File.OpenWrite(localFileName);
using (StreamWriter sw = new StreamWriter(fileStream, enc))
{  /* ... */ }

To be sure, you could convert everything to UTF-8 and store your file as UTF-8 always. That way you are never left with the need to guess the encoding when reading the file.


text:
Q: http://guides.rubyonrails.org/getting_started.html Rails errors: NoMethodError in Articles#show I am new to Rails and seeing this error when submitting the form at localhost:3000/articles/new
NoMethodError in Articles#show

I am following along the http://guides.rubyonrails.org/getting_started.html tutorial step for step.
class ArticlesController < ApplicationController
  def new
  end

  def create
    @article = Article.new(article_params)

    @article.save
    redirect_to @article
  end

  private
    def article_params
      params.require(:article).permit(:title, :text)
    end

    def show
      @article = Article.find(params[:id])
    end

    def index
      @articles = Article.all
    end
end

Here is the link to the Github repository for my code.  I'm using Rails version 4.1.7.  Any help will be appreciated!
https://github.com/z20/rails_start

A: Your code:
class ArticlesController < ApplicationController
  def new
  end

  def create
    @article = Article.new(article_params)

    @article.save
    redirect_to @article
  end

  private
    def article_params
      params.require(:article).permit(:title, :text)
    end

    def show
      @article = Article.find(params[:id])
    end

    def index
      @articles = Article.all
    end
end

should be changed to:
class ArticlesController < ApplicationController
  def new
  end

  def create
    @article = Article.new(article_params)

    @article.save
    redirect_to @article
  end

  def show
    @article = Article.find(params[:id])
  end

  def index
    @articles = Article.all
  end

  private
    def article_params
      params.require(:article).permit(:title, :text)
    end
end

show is private in your code, and should be public. Move the private after your actions. When you set private in a class, everything that comes after that private will be inaccessible outside of that specific class.


text:
Q: Encoding of 2-bit numbers A + B Consider two 2-bit binary numbers A and B ranging from integers [0,3]. Each bit in A and B have an equal probability of being either 0 0r 1.
Consider an encoding scheme for A+B (where A+B ranges from [0,6]), such that the decoder has access to any single bit in A+B. The question is: what is the encoding scheme that leaves the decoder with an equal probability of A, B being one among {0,1,2,3} by looking at any one of the bits in A+B?
Example: encoding scheme {000,001,010,011,100,101,110} leaves A with equal probability on {0,1,2,3} if we look LSB but not true for MSB.
In addition, the encoder should also satisfy the boolean addition properties. For example, if 0 is encoded as 'abc', $a,b,c \in \{0,1\}$ and 1 is encoded as 001, 0 + 1 (abc+001) should yield 001.
Any such boolean encoders or suggestions/references?

A: If I have understood your question correctly, there can be no such encoding, even if we neglect the "addition property".
Namely, look at every single bit in the output. We can prove that this bit must be "periodic with period $4$", i.e. it must be the same on encoding the sums $n$ and $n+4$, for $n=0,1,2$. As every bit in a multi-bit encoding must be periodic, this means that, no matter how many bits we use, we cannot possibly distinguish, say, sum $0$ from $4$, or $1$ from $5$, or $2$ from $6$.
Let $b_n\in \{0,1\}$ be a single-bit encoding of $n=0,1,2,\ldots,6$. We can see that $\frac{1}{16}(b_n+b_{n+1}+b_{n+2}+b_{n+3})$ (for $n=0,1,2,3$) is the same as the probability that $A=n$ and the encoding of $A+B$ is $1$. This is proportional (by a constant factor independent on $n$) to the conditional probability that $A=n$ assuming encoding of $A+B$ is $1$. But we want that conditional probability to stay the same, independent on $n$. Thus:
$$\frac{1}{16}(b_n+b_{n+1}+b_{n+2}+b_{n+3})=\frac{1}{16}(b_{n+1}+b_{n+2}+b_{n+3}+b_{n+4})$$
for $n=0,1,2$, which implies $b_{n+4}=b_n$.
Note that, in your example, both bits $0$ (LSB) and $1$ are periodic with period $4$ and both satisfy the desired property. The bit $2$ (MSB) is not periodic, and that is why (as per above proof) it cannot satisfy the desired property.

A: Here is a truth table of the addition encoding.
A, B and A+B columns represent the decimal value of addition.
The bits s2, s1, s0 represent the binary representation of the addition.

We observe that the frequency distribution of the 1s in s2, s1 and s0 and note that s1 and s0 have 50% probability of a 1 (or 0) whereas s2 is skewed with a probability of 6/16 (for 1s).
We also note that an encoding scheme is an automorphism in $GF(7)$ composed with a permutation of the resulting bits of s2, s1, s0. So, regardless of the permutation scheme used for the encoding, we need to use the non-skewed bit ie., s1 or s0 in the original unpermuted binary encoding of the sum if we want A+B to be 0, 1, 2 or 3 with equal probabilities after looking at just a single bit of the output.


text:
Q: How do I convert RGB decimal to Hex colors in JavaScript? I have RGB colors in the form:
[0.00784, 0.62745, 0.77647]

I would like to convert them to hex color, but I'm not sure how. I've seen other types of RGB components converted to hex, but not in this format.

A: Multiply all the values by 255, round it and then use the solution from this question.

const componentToHex = c => {
  const hex = c.toString(16)
  return hex.length === 1 ? '0' + hex : hex
}

const rgbToHex = (r, g, b) => '#' + [r, g, b].map(componentToHex).join('')

const rgb = [0.00784, 0.62745, 0.77647].map(x => Math.round(x * 255))
console.log(rgbToHex(...rgb))


text:
Q: GCP cloud spanner, is it serverless? I could find out the GCP Cloud SQL is not serverless. But I could not find about the same with GCP Cloud Spanner.
Is GCP cloud spanner serverless?

A: GCP Cloud Spanner uses managed instances in the same way GCP Cloud SQL does, so they are not serverless.

A: The GCP cloud spanner runs on a virtual server. Even though you don't get to configure the virtual server, it runs in the background. Therefore, cloud spanner is NOT serverless.
GCP Serverless Database and storages: Memorystore, Cloud Datastore, Firestore, Cloud storage, Firebase
GCP Non-serverless Database and storages: Cloud SQL, Cloud Spanner, Cloud Bigtable, BigQuery


text:
Q: Subgroup generated by a reflection is not normal in the dihedral group of order $2n$ Let $D_{2n}$ be the dihedral group of order $2n$. Then, the subgroup generated by a reflection is not normal.
I think I've come up with a proof for a converse that if an element is not $\left\langle h\right\rangle$ for $H$ the subgroup consisting of $n$ rotations, then its square equals the identity thus it is a reflection.
However, I am struggling to prove why a reflection would not be normal in this case. Is this because a reflection $y\in Y$ for $g \in G$ would not give $ghg^{-1}\in Y$ because we have the property $y^2=e$?
Any help will be appreciated!

A: Note $\mathcal R_n\cap\langle h\rangle=\{e\}$ where $h$ is a reflection symmetry in the dihedral group $\mathcal D_n$ and where $\mathcal R_n$ denotes the $\mathcal D_n$ subgroup of all rotation symmetries. Since $\mathcal R_n\lhd\mathcal D_n$ then we have $$h\in\mathcal Z(\mathcal D_n)\iff\langle h\rangle\lhd\mathcal D_n\implies\mathcal D_n=\mathcal R_n\oplus\langle h\rangle$$ As $\mathcal D_n$ is non-abelian it is not the product of abelian groups and thus $\langle h\rangle$ is not normal in $\mathcal D_n$.


text:
Q: Intellisense comments inside class functions? Is there any way to make C++ intellisense comments appear in the class member/function list when using it from within a class function in Visual Studio? Let me give an example.
Say we have a Dog and a Cat class like below. Let's assume the Cat has a "dog" reference to a Dog instance. Notice the Xml comments that have been added to each member function, specifically, the isBarking function for this example.
class Dog
{
    ///Makes the dog bark.
    void bark() { if (isBarking()) { /*woof woof*/ } }

    ///Is the dog barking?
    ///<return>This dog has no bark, so it always returns false.</return>
    bool isBarking() { return false; }
}

class Cat
{
    ///Should the cat run?
    ///<return>Always true if the dog is barking, otherwise false.</return>
    bool run() { return dog.isBarking(); }
}

When typing the isBarking function (or hovering your mouse over it) inside the Cat's run function, the intellisense summary and return comment for the isBarking function is displayed as per normal.
However, when typing the isBarking function (or hovering your mouse over it) inside the Dog's bark function, the intellisense summary and return comment is NOT displayed for the isBarking function. Is there anyway to get it to display?

A: Visual Studio never displays <return> statements, they are meant for some other purpose. When you are extracting documentation out of your code, <return>s are used. Visual Studio displays  statements only.
I just copied your code in VS 2013, I can see  on mouse hover and while typing as well.
Just check your VS settings, Go to Visual Studio Editor, Edit Menu-> Intellisense. To turn on/off Quick Info, Parameter Info, etc.


text:
Q: deserialize javascript date on server asp.net mvc 3 I've been struggling with this issue for a while. I'm trying to send an object to the client. Once the client updates the object I'd like to post it back to the server and save it in my database. The first part works fine. However, when I send it back all the dates are messed up and start for year 0001. I assume that's because it can't deserialize the date. Howe can I post a json object with a date property and deserialize it into a type on the server with asp.net mvc 3?
group is
public class Group
{
    public Group();

    public string CreatedBy { get; set; }
    public DateTime CreatedOn { get; set; }
    public string Description { get; set; }
    public string Name{ get; set; }
    public string Status { get; set; }
    public string UpdatedBy { get; set; }
    public DateTime UpdatedOn { get; set; }
}

while
    public JsonResult updateGroup(Group group)
    {
        var result = Repository.updateGroup(group);
        return Json(result, JsonRequestBehavior.AllowGet);
    }

and on the client I got
    $.ajax({
        url: '../updateGroup',
        type: 'POST',
        data: JSON.stringify(group),
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function(){ success(); }
    });

A: ASP.NET MVC 3 uses the JavaScriptSerializer to deserialize values back. Quoting from the documentation of this class:

Date object, represented in JSON as
  "\/Date(number of ticks)\/". The
  number of ticks is a positive or
  negative long value that indicates the
  number of ticks (milliseconds) that
  have elapsed since midnight 01
  January, 1970 UTC.
The maximum supported date value is
  MaxValue (12/31/9999 11:59:59 PM) and
  the minimum supported date value is
  MinValue (1/1/0001 12:00:00 AM).

This basically means that your request object has to look something like this:
{ CreatedOn: '\/Date(1299098853123)\/', CreatedBy: 'foo', ... }

So here's how you could proceed:
// taking the local time but this could be any javascript Date object
var now = new Date();
var group = {
    CreatedBy: 'foo',
    CreatedOn: '\/Date(' + now.getTime() + ')\/',
    Description: 'some description',
    Name: 'some name',
    etc...
};

Of course because we are now working with UTC don't forget to compensate to local time on your server if you ever need to work with local time (UTC is preferred):
public ActionResult UpdateGroup(Group group)
{
    DateTime serverCreatedOn = group.CreatedOn.ToLocalTime();
    ...
}

Also don't hardcode urls like this:
url: '../updateGroup'

Always use URL helpers when dealing with urls or you might get bad surprises when you ship:
url: '@Url.Action("updateGroup")'

UPDATE:
Try encoding the date like this:
// taking the local time but this could be any javascript Date object
var now = new Date();
var group = {
    CreatedBy: 'foo',
    CreatedOn: now.toUTCString(),
    Description: 'some description',
    Name: 'some name',
    etc...
};

A: Thanks for your help Darin. the UTC string didn't quite work but I got this to work
    var now = new Date();
    group.CreatedOn = now.toLocaleString();

and even
    var now = new Date();
    group.CreatedOn = now;

works


text:
Q: How to create an empty jQuery result
Edit: As of jQuery 1.4, using $() will work as described below.

I need to loop through an array and create a number of elements which I want to have in a single jQuery result object.
for (var i = 0; i < 10; ++i) {
    $myJQueryObj = $myJQueryObj.add($("blahblah"));
}

The problem with this, however, is that you need a jQuery object to begin with, and you obviously want to start it empty. In the above example, how should I initialise $myJQueryObj ?
The following examples do not work, as they all select the document object:
$('')
$()
$(null)
$(false)

These do work... but...
$('#nonExistantElement')  // yuck
$().slice(0,0)            // surely there's a nicer way?

Is there a better way?

A: Yep. Try $([]). The reason $() doesn't work is because that jQuery expects a context, and without any supplied, will default to document as the context. Many things depend on this assumption being true, so changing $() to mean "give me the empty set" would be problematic at best.

A: Ah, I figured it out just after I wrote the question. Here's what I found, in case anyone else is interested:
$([])