text:
Q: Как выбрать до 3 карточек, остальные сделать неактивными, все записать в localstorage и при загрузке все выводить как было? Нужно выбирать до 3х карточек.
При достижении лимита отключаем остальные карточки.
Карточки по ID записываем в localStorage. И при загрузке страницы расставляем выбор как было.
Проблема в том, что при загрузке не все неактивные карточки становятся неактивными. А также можно выбрать больше ограничения. Казалось бы элементарная задача, а превратилась в нечто невозможное..

jsFiddle https://jsfiddle.net/Vaniljs/19muw4d7/59/

const limit = 3;
var arrForCheckedItem = []; // массив для сохранения el в localStorage

document.addEventListener('click', ({ target: t }) => {
  if (t.classList.contains('product')) {
    if (!t.classList.contains('unchecked')) {
        arrForCheckedItem = []; // обнуляем массив, чтобы не копился
      t.classList.toggle('checked');
      document.querySelectorAll('.product.checked').forEach(i => {
    if (i.classList.contains('checked')) {
            arrForCheckedItem.push(i.dataset.productid); // Сохраняем выбранные el в массив
        }
    })
      localStorage.setItem('checked_items', arrForCheckedItem); // Сохраняем массив в localStorage
      const allChecked = document.querySelectorAll('.product.checked').length >= limit;
      document.querySelectorAll('.product:not(.checked)').forEach(n => {
        n.classList.toggle('unchecked', allChecked);
      });
    }
  }
  console.log(localStorage.getItem('checked_items')); // Проверка содержимого в localStorage
});

// ОТМЕЧАЕМ ВЫБРАННЫЕ И НЕВЫБРАННЫЕ ПРИ ЗАГРУЗКЕ СТРАНИЦЫ

window.addEventListener('load', () => {
    let arrFromStorage = localStorage.getItem('checked_items'); // выгружаем данные из localStorage
  let allCards = document.querySelectorAll('.product.slick-slide'); // выбираем все карточки
    if (arrFromStorage.length) { // если localStorage существует
        arrFromStorage.split(',').map(itemFromStorage => { // режем строку из localStorage в массив и перебираем
            allCards.forEach(itemProduct => {
                if (itemProduct.dataset.productid == itemFromStorage) { // если у карточки такой же id - отмечаем ее выбранной
                    itemProduct.classList.add('checked')
                }
        if (document.querySelectorAll('.product.slick-slide.checked').length >= limit && itemProduct.dataset.productid != itemFromStorage) { // если у карточки не такой же id b выбранных меньше лимита - отмечаем ее не выбранной
                    itemProduct.classList.add('unchecked')
                }
            })
        })
    }
})
div:not(.product) {
    display: flex;
}

.product {
    display: block;
    width: 100px;
    height: 100px;
    margin: 20px;
    background-color: gray;
    border: 2px solid gray;
    cursor: pointer;
}

.product.checked {
    border: 2px solid green;
    background-color: lightgray;
}

.product.unchecked {
    border: 2px solid red;
    background-color: darkgray;
    cursor: not-allowed;
}

1

2

3

4

5

6

A: Сделал форк от вашего fiddle: https://jsfiddle.net/4h0cu1wo/
Мне кажется, что выделение красным стоит сделать с помощью css. Таким образом, можно выделять красным все те, кто не имеет класс .checked, но только в случае, если в родителях есть класс .limit.
Если в процессе сохранить список с массивом из трех элементов, а потом уменьшить лимит до одного, выделен будет только первый, так как загрузка фактически имитирует последовательные нажатия по карточкам.
index.js:
const limit = 3; // Какой лимит выделяемых элементов

let selected = 0; // Количество выделенных на данный момент элементов

const cards = document.getElementById('cards') // Ссылка на контейнер всех карточек
cards.addEventListener('click', ({ target }) => {
    if (target.dataset.productid) select(target) // Если нажали по карточке, пытаемся ее выделить
});

window.addEventListener('load', () => load()); // Выполняем загрузку при запуске страницы

// Выделение передаваемого элемента
function select(element) {
    // Если лимит не достигнут или мы нажимаем по выделенному элементу...
    if (selected < limit || element.classList.contains('checked')) {
        element.classList.toggle('checked') // Переключаем .checked
        selected += element.classList.contains('checked') ? 1 : -1 // Если .checked был добавлен, инкрементируем счетчик
        cards.classList.toggle('limit', selected >= limit) // Если достигли лимита, добавляем класс .limit в контейнер
        if (selected >= limit) save() // А так же, при достижении лимита сохраняем полученный список
    }
}

// Сохранение списка выделенных карточек
function save() {
    const items = []
    // Проодим по всем элементам, у которых есть класс .checked
    cards.querySelectorAll('.checked').forEach(element => items.push(element.dataset.productid));
    localStorage.setItem('checked_items', items); // Сохраняем их в LocalStorage
}

// Загрузка списка выделенных карточек
function load() {
  const items = localStorage.getItem('checked_items');
  items.split(',').forEach(id => select(cards.querySelector(`[data-productid="${id}"]`))) // Передаем на выделение карточку с указанным id в dataset
}

index.css:
div#cards {
  display: flex;
}

.product {
  display: block;
  width: 100px;
  height: 100px;
  margin: 20px;
  background-color: gray;
  border: 2px solid gray;
  cursor: pointer;
}

.limit {
  .product {
    border: 2px solid red;
    background-color: darkgray;

    &:not(.checked) {
      cursor: not-allowed;
    }
  }
}

.product.checked {
  border: 2px solid green;
  background-color: lightgray;
}

index.html:

1

2

3

4

5

6

A:

window._cardsSelector = {
  _f: {},
  defaults: {
    cardsLimit: 3,
    selectors: {
      card: 'div.card'
    }
  }
};

window._cardsSelector._f.save = () => {
  let idList = [];

  $(`${window._cardsSelector.defaults.selectors.card}.selected`)
    .each((i, item) => {
      idList.push($(item).data('card-id'));
    });

  localStorage.setItem('selected_cards', JSON.stringify(idList));
};

window._cardsSelector._f.load = () => {
  let ids = JSON.parse(localStorage.getItem('selected_cards', '[]'));
  ids.forEach(i => $(`div.card[data-card-id=${i}]`).addClass('selected'));
  window._cardsSelector._f.check();
};

window._cardsSelector._f.check = () => {
  let limit = window._cardsSelector.defaults.cardsLimit,
    defaultSelector = $(`${window._cardsSelector.defaults.selectors.card}.selected`);

  if (defaultSelector.length === limit) {
    $(`${window._cardsSelector.defaults.selectors.card}:not(.selected)`)
      .addClass('disabled');
  } else {
    $(`${window._cardsSelector.defaults.selectors.card}.disabled`)
      .removeClass('disabled');
  }

  window._cardsSelector._f.save();
};

$(document).ready(function() {
  window._cardsSelector._f.load();

  $(window._cardsSelector.defaults.selectors.card)
    .click(function() {
      $(this).toggleClass('selected');
      window._cardsSelector._f.check();
    });
});
.cards {
  width: 98% !important;
  margin: 8px auto;
}

.cards>.card {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 150px;
  max-width: 200px;
  padding: 12px;
  margin: 4px;
  box-shadow: 0 0 1px gray
}

.selected {
  background: rgba(0, 160, 0, 0.07);
}

.disabled {
  background: rgba(0, 0, 0, 0.07);
}

    Card Item 1

    Card Item 2

    Card Item 3

    Card Item 4

    Card Item 5

    Card Item 6


text:
Q: Mysql autoincrement bug in insert select Can anyone suggest me the workaround for the following bug in mysql.
  http://bugs.mysql.com/bug.php?id=61058

This bug was reported long ago (2007) with mysql 5.0, but i am still facing same issue with mysql 5.6. I have followed this post which first gave some insight for this problem.
Mysql auto increment jumps when insert-select
Followed the post as some one suggested preferably setting
ALTER TABLE `test` AUTO_INCREMENT = 1;

which will not work in my case where i have a stored procedure which will run in background as an event for a specified time.
Can anyone please suggest me for a workaround....??
Thanks in advance

A: First, you should make sure that mysql is up to date and second try to reset auto increment like below:
ALTER TABLE tablename AUTO_INCREMENT = 1

A: You can change innodb_autoinc_lock_mode=0 ("traditional" lock mode) from mysql.ini to  avoid skipping values in primary key in some cases. See the manual innodb auto increment handling  for more details.

As per manual  'The traditional lock mode option is provided for backward compatibility, performance testing, and working around issues with "mixed-mode inserts", due to possible differences in semantics'.
'In this lock mode, all "INSERT-like" statements obtain a special table-level AUTO-INC lock for inserts into tables with AUTO_INCREMENT columns. This lock is normally held to the end of the statement (not to the end of the transaction) to ensure that auto-increment values are assigned in a predictable and repeatable order for a given sequence of INSERT statements, and to ensure that auto-increment values assigned by any given statement are consecutive'.

Another thing to check is the value of the auto_increment_increment config variable. It's 1 by default, but you may have changed this. it is very uncommon to set it to something higher than 1 or 2, but possible.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Including images in GeoJSON Is there a correct way of including links to images within geoJSON?
This is the FeatureCollection I have for an object on my site:
{
  "type": "FeatureCollection",
  "features": [
    {
      "id": 1234,
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          -0.322825,
          51.065361
        ]
      },
      "properties": {
        "popupContent": "In loving memory of\r\nGordon Wiseman\r\n15.4.30 ~ 11.8.06\r\nWho spent many happy hours\r\nin this park"
      }
    }
  ]
}

I also want to include the links to multiple images.  Is it OK to add another property? For example:
"properties": {
    "popupContent": "In loving memory of\r\nGordon Wiseman\r\n15.4.30 ~ 11.8.06\r\nWho spent many happy hours\r\nin this park",
    "media": [
        "https://example.com/image1.jpg",
        "https://example.com/image2.jpg"
    ]
}

Or is there a better / more standard way of doing it?

A: AFAIK GeoJSON is standardized by the Internet Engineering Task Force (IETF), and the standard mainly defines the implementation of geographic objects.
The properties are based on and extended from the {key: value} structure of JSON itself; you can populate it with anything that fits this concept.
The exact contents should be tailored to the parsing capabilities of your target software; it's likely some frameworks/systems can automatically parse image URLs from a dedicated property.
For interchangeability, I would probably stick to the standard properties: {key: value}, just like you did.
In many applications, properties are treated as attributes/field/columns...you can add as many as the target system allows. However, I would avoid furrther nesting of property objects.


text:
Q: Ошибка в использование requests socks5 с threading Помогите понять в чем  ошибка и как исправить, я как думаю что socks не может запускаться с разными ip в разных потоках. Как это можно исправить.
import requests
import sys
import time
from datetime import datetime,timedelta
from threading import Thread

class my_proxy():
    def manual_list(self):
        list_proxy = []
        list_proxy.append(['109.172.111.30', 'port', 'login', 'pass','port'])
        list_proxy.append(['149.126.232.99', 'port', 'login', 'pass','port'])
        list_proxy.append(['185.29.124.192', 'port', 'login', 'pass','port'])

        return list_proxy

c_my_proxy = my_proxy()
list_proxy = c_my_proxy.manual_list()

def fff(thread_number):
    s = requests.Session()
    proxies = dict(http="socks5://" + str(list_proxy[thread_number][2]) + ":" + str(
        list_proxy[thread_number][3]) + "@" + str(list_proxy[thread_number][0]) + ":" + str(
        list_proxy[thread_number][4]) + "",
                  https="socks5://" + str(list_proxy[thread_number][2]) + ":" + str(
                      list_proxy[thread_number][3]) + "@" + str(list_proxy[thread_number][0]) + ":" + str(
                      list_proxy[thread_number][4]) + "")
    print(thread_number, ' -- ', proxies)

    resp = s.get('http://icanhazip.com/',proxies=proxies)
    print(thread_number,' - - - -  ',resp.text)

for thread_number in range(1,10):
    if thread_number >=1:
        th = Thread(target=fff, args=(thread_number, ))
        th.start()
        time.sleep(5)

Первый поток отрабатывает запрос, после идет ошибка
1  --  {'http': 'socks5://login:pass@149.126.232.99:port', 'https': 'socks5://login:pass@149.126.232.99:port'}
1  - - - -   149.126.232.99

2  --  {'http': 'socks5://login:pass@185.29.124.192:port', 'https': 'socks5://login:pass@185.29.124.192:port'}
Exception in thread Thread-2:
Traceback (most recent call last):
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\socks.py", line 809, in connect
    negotiate(self, dest_addr, dest_port)
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\socks.py", line 443, in _negotiate_SOCKS5
    self.proxy_peername, self.proxy_sockname = self._SOCKS5_request(
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\socks.py", line 533, in _SOCKS5_request
    raise SOCKS5Error("{:#04x}: {}".format(status, error))
socks.SOCKS5Error: 0x02: Connection not allowed by ruleset

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\urllib3\contrib\socks.py", line 96, in _new_conn
    conn = socks.create_connection(
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\socks.py", line 209, in create_connection
    raise err
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\socks.py", line 199, in create_connection
    sock.connect((remote_host, remote_port))
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\socks.py", line 47, in wrapper
    return function(*args, **kwargs)
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\socks.py", line 814, in connect
    raise GeneralProxyError("Socket error", error)
socks.GeneralProxyError: Socket error: 0x02: Connection not allowed by ruleset

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\urllib3\connectionpool.py", line 703, in urlopen
    httplib_response = self._make_request(
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\urllib3\connectionpool.py", line 398, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\urllib3\connection.py", line 239, in request
    super(HTTPConnection, self).request(method, url, body=body, headers=headers)
  File "C:\Users\Hitro\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1285, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "C:\Users\Hitro\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1331, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "C:\Users\Hitro\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1280, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "C:\Users\Hitro\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1040, in _send_output
    self.send(msg)
  File "C:\Users\Hitro\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 980, in send
    self.connect()
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\urllib3\connection.py", line 205, in connect
    conn = self._new_conn()
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\urllib3\contrib\socks.py", line 127, in _new_conn
    raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.contrib.socks.SOCKSConnection object at 0x000001DB39B98D00>: Failed to establish a new connection: 0x02: Connection not allowed by ruleset

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\requests\adapters.py", line 489, in send
    resp = conn.urlopen(
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\urllib3\connectionpool.py", line 787, in urlopen
    retries = retries.increment(
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\urllib3\util\retry.py", line 592, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: SOCKSHTTPConnectionPool(host='icanhazip.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.contrib.socks.SOCKSConnection object at 0x000001DB39B98D00>: Failed to establish a new connection: 0x02: Connection not allowed by ruleset'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Hitro\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner
    self.run()
  File "C:\Users\Hitro\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run
    self._target(*self._args, **self._kwargs)
  File "D:\pythonProject\dparsingsale\conn\test2.py", line 39, in fff
    resp = s.get('http://icanhazip.com/',proxies=proxies)
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\requests\sessions.py", line 600, in get
    return self.request("GET", url, **kwargs)
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\requests\sessions.py", line 587, in request
    resp = self.send(prep, **send_kwargs)
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\requests\sessions.py", line 701, in send
    r = adapter.send(request, **kwargs)
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\requests\adapters.py", line 565, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: SOCKSHTTPConnectionPool(host='icanhazip.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.contrib.socks.SOCKSConnection object at 0x000001DB39B98D00>: Failed to establish a new connection: 0x02: Connection not allowed by ruleset'))
Traceback (most recent call last):
  File "D:\pythonProject\dparsingsale\conn\test2.py", line 48, in <module>
    time.sleep(5)
KeyboardInterrupt

Process finished with exit code -1073741510 (0xC000013A: interrupted by Ctrl+C)

A: Как пример.
from threading import Thread
import requests

def fff(thread_number, proxies):
    try:
        resp = requests.get('http://icanhazip.com/',proxies=proxies)
        txt = resp.text.strip()
    except Exception as ex:
        txt = ex

    print(thread_number,'  - -  ',txt)

list_proxy =[{'http': 'socks5://103.214.112.240:32323',
              'https': 'socks5://103.214.112.240:32323'},
             {'http': 'socks5://138.94.92.26:7497',
              'https': 'socks5://138.94.92.26:7497'},
             {'http': 'socks5://170.238.79.2:7497',
              'https': 'socks5://170.238.79.2:7497'}]
# login = 'IAmGroot'
# passw ="12345"
#
# list_proxy =[{'http': f'socks5://{login}:{passw}@149.126.232.99:1234',
#               'https': f'socks5://{login}:{passw}@149.126.232.99:1234'},
#              {'http': f'socks5://{login}:{passw}@149.126.232.99:8888',
#               'https': f'socks5://{login}:{passw}@149.126.232.99:8888' }
#              ]

for thread_number, proxy in enumerate(list_proxy):
    th = Thread(target=fff, args=(thread_number, proxy, ))
    th.start()

1   - -   138.94.92.26
0   - -   103.214.112.240
2   - -   170.238.79.2


text:
Q: Bootstrap Checbox Modal Not Working Bootstrap modal checkbox not working when checkbox is checked.
The condition is when user click the checkbox the bootstrap modal popup should be displayed
Bootstrap Version 3.3.6
Jquery Version 2.1.3

$(function()
{
  $('#tos-checkbox').click(function()
        {
            if ($('#tos-checkbox').is(":checked")) {
                $('#tosmodal').modal('show');
            }else {
                $('#tosmodal').modal('hide');
            }
        });
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

<input id="tos-checkbox" type="checkbox">
          I agree to the Terms And Conditions.

          <button type="button" class="close" >×</button>

Modal Header

Some text in the modal.

          <button type="button"  class="btn btn-default" data-dismiss="modal" >Close</button>

A: change ther order of JQuery. Put JQuery to very first

$(function()
{
  $('#tos-checkbox').click(function()
        {
            if ($('#tos-checkbox').is(":checked")) {
                $('#tosmodal').modal('show');
            }else {
                $('#tosmodal').modal('hide');
            }
        });
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

<input id="tos-checkbox" type="checkbox">
          I agree to the Terms And Conditions.

          <button type="button" class="close" >×</button>

Modal Header

Some text in the modal.

          <button type="button"  class="btn btn-default" data-dismiss="modal" >Close</button>

A: JQUERY is required to use bootstrap.js. The reason why you need to rearrange the order you call bootstrap and jquery is that you need to call jquery first before bootstrap.js. Your question's been answered. I just want to take part in explaining. Hope it helps.


text:
Q: rubygems' Could not find gem > 'win32console (>= 0, runtime)' I'm trying to install the sample app located here: http://jhollingworth.com/2010/12/26/web-automation-using-cucumber-capybara/
One of the initial steps for setting this up are running bundle in the install location. When I execute bundle I get the following error:

C:\Capybara\jhollingworth-.Net-Web-Automation-example>bundle
  Your Gemfile doesn't have any sources.
  You can add one with a line like
  'source :rubygems' Could not find gem
  'win32console (>= 0, runtime)' in any
  of the gem sources listed in your
  Gemfile.

When I check the bundle Gemfile it does have  "http://rubygems.org" included
Can anyone shed some light on the above. Google return similar results but for different packages (e.g sql)
My GemFile currently contains :
source "rubygems.org"; Is that the right format?

A: It looks like your gemfile doesn't have any sources listed. Add 'source :rubygems' to the top of your Gemfile. If that doesn't solve your problem, post the contents of your Gemfile.


text:
Q: emptying some `li` from listview using jQuery Mobile I have a working listview populated by js.  I wanted to add an option to hide the listview but retain the listdivider.  I can only come up with this:
$('#myList').empty()

and this emmpties everyrthing.  How can I empty the list but not the listdivider?
many thanks.

A: Without seeing your HTML I'm assuming here, but try this:
$('#myList li').not("#divider").remove()

This will remove each li element contained in #myList, except the li with an id of divider.
You will need to put whatever valid selector will catch your dividing element in the not() method.


text:
Q: How do you nest XSL selects so you don't have to use the same XPaths I have the below XSL which works as required. However it feels messy having to reuse the same Customer/Personnel XPath over and over again. Is there a way I could nest the XSL so that anything within that nested node uses the same prefix XPath.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/">
    <root>
        <ContactInternal>
            <xsl:attribute name="UserShortName" select="Customer/Personnel/Party/ShortName" />
            <xsl:attribute name="UserName" select="Customer/Personnel/Party/Name" />
            <xsl:attribute name="Email" select="Customer/Personnel/Party/ContactAddresses/ContactAddress/EmailAddress/EMail" />
            <xsl:if test="Customer/Personnel/Party/ContactAddresses/ContactAddress/Telephone/Number">
              <xsl:attribute name="Telephone" select="Customer/Personnel/Party/ContactAddresses/ContactAddress/Telephone/Number" />
            </xsl:if>
            <xsl:if test="Customer/Personnel/JobTitle">
              <xsl:attribute name="JobTitle" select="Customer/Personnel/JobTitle" />
            </xsl:if>
            <xsl:if test="Customer/Personnel/Branch/Code">
              <xsl:attribute name="BranchCode" select="Customer/Personnel/Branch/Code" />
            </xsl:if>
        </ContactInternal>
    </root>
</xsl:template>
</xsl:stylesheet>

Sorry if this has been asked before. I have tried to have a look around for an answer but feel I may just be searching for the wrong thing.
Thanks in advance for any advice.

A: You can use variables to store the nodes that you're using more than once:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/">
    <xsl:variable name="personnel"
                  select="Customer/Personnel" />
    <xsl:variable name="party"
                  select="$personnel/Party" />
    <xsl:variable name="contactAddress"
                  select="$party/ContactAddresses/ContactAddress" />
    <root>
        <ContactInternal>
            <xsl:attribute name="UserShortName" select="$party/ShortName" />
            <xsl:attribute name="UserName" select="$party/Name" />
            <xsl:attribute name="Email" select="$contactAddress/EmailAddress/EMail" />
            <xsl:if test="$contactAddress/Telephone/Number">
              <xsl:attribute name="Telephone" select="$contactAddress/Telephone/Number" />
            </xsl:if>
            <xsl:if test="$personnel/JobTitle">
              <xsl:attribute name="JobTitle" select="$personnel/JobTitle" />
            </xsl:if>
            <xsl:if test="$personnel/Branch/Code">
              <xsl:attribute name="BranchCode" select="Customer/Personnel/Branch/Code" />
            </xsl:if>
        </ContactInternal>
    </root>
</xsl:template>

Additionally, you can make this less verbose by using attribute value templates:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/">
    <xsl:variable name="personnel"
                  select="Customer/Personnel" />
    <xsl:variable name="party"
                  select="$personnel/Party" />
    <xsl:variable name="contactAddress"
                  select="$party/ContactAddresses/ContactAddress" />
    <root>
        <ContactInternal UserShortName="{ $party/ShortName }"
                         UserName="{ $party/Name }"
                         Email="{ $contactAddress/EmailAddress/EMail }">
            <xsl:if test="$contactAddress/Telephone/Number">
              <xsl:attribute name="Telephone" select="$contactAddress/Telephone/Number" />
            </xsl:if>
            <xsl:if test="$personnel/JobTitle">
              <xsl:attribute name="JobTitle" select="$personnel/JobTitle" />
            </xsl:if>
            <xsl:if test="$personnel/Branch/Code">
              <xsl:attribute name="BranchCode" select="Customer/Personnel/Branch/Code" />
            </xsl:if>
        </ContactInternal>
    </root>
</xsl:template>

A: Further to JLRishe's answer, in XSLT 3.0 you can make this more compact still:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="3.0">
<xsl:template match="/">
    <xsl:variable name="personnel"
                  select="Customer/Personnel" />
    <xsl:variable name="party"
                  select="$personnel/Party" />
    <xsl:variable name="contactAddress"
                  select="$party/ContactAddresses/ContactAddress" />
    <root>
        <ContactInternal UserShortName="{ $party/ShortName }"
                         UserName="{ $party/Name }"
                         Email="{ $contactAddress/EmailAddress/EMail }">
            <xsl:where-populated>
              <xsl:attribute name="Telephone"
                             select="$contactAddress/Telephone/Number" />
              <xsl:attribute name="JobTitle"
                             select="$personnel/JobTitle" />
              <xsl:attribute name="BranchCode"
                             select="$personnel/Branch/Code" />
            </xsl:where-populated>
        </ContactInternal>
    </root>
</xsl:template>

A: This can also be done with template rules:
<xsl:template match="/">
  <root>
    <ContactInternal>
       <xsl:apply-templates/>
    </ContactInternal>
  </root>
</xsl:template>

<xsl:template match="ShortName">
  <xsl:attribute name="UserShortName" select="."/>
</xsl:template>

<xsl:template match="Name">
  <xsl:attribute name="UserName" select="."/>
</xsl:template>

<xsl:template match="EMail">
  <xsl:attribute name="Email" select="."/>
</xsl:template>

...

(qualifying the patterns as, for example match="Party/Name" if necessary for disambiguation).


text:
Q: MongoId with Hash field: values are different with MongoDB and with Rails I have a model in MongoId with this field:
  field :m, as: :monthly, type: Hash

The structure is per month hash with month number as key and quantity as values
When querying in Rails console a specific row I have the following:
<_id: 5ddf95cd1dd6150008356ec6, m(monthly): {"1"=>0, "2"=>0, "3"=>3, "4"=>0, "5"=>0, "6"=>0, "7"=>0, "8"=>0, "9"=>0, "10"=>0, "11"=>0, "12"=>0}>

When querying in MongoDB console the same id I have the following:
db.myCollection.find({"_id": ObjectId("5ddf95cd1dd6150008356ec6")});
{ "_id" : ObjectId("5ddf95cd1dd6150008356ec6"), "m" : { "1" : 0, "2" : 0, "3" : 0, "4" : 0, "5" : 0, "6" : 0, "7" : 0, "8" : 0, "9" : 0, "10" : 0, "11" : 2, "12" : 0 } }

*

*For monthly[3] I have 0 in MongoDb console and 3 in Rails console

*For monthly[11] I have 2 in MongoDb console and 0 in Rails console

I can't understand why
My MongoDb versions is v3.4.13 (shell and server)
And I am in Rails 5.2.2 with Ruby 2.4.5 and MongoId 7.0.2
EDIT :
Here is info about the queries with MongoId and the result:
MyCollection.where(id: '5ddf95cd1dd6150008356ec6').first

<MyCollection _id: 5ddf95cd1dd6150008356ec6, m(monthly): {"1"=>0, "2"=>0, "3"=>3, "4"=>0, "5"=>0, "6"=>0, "7"=>0, "8"=>0, "9"=>0, "10"=>0, "11"=>0, "12"=>1}>

MyCollection.collection.find(_id: BSON::ObjectId('5ddf95cd1dd6150008356ec6')).first

{"_id"=>BSON::ObjectId('5ddf95cd1dd6150008356ec6'), "m"=>{"1"=>0, "2"=>0, "3"=>3, "4"=>0, "5"=>0, "6"=>0, "7"=>0, "8"=>0, "9"=>0, "10"=>0, "11"=>0, "12"=>1} }

My issue is only for this id 5ddf95cd1dd6150008356ec6, for other id data in mongodb and mongoid are matching

A: What was the Mongoid query?
Use direct collection access to retrieve the raw document using the driver and compare to the Mongoid result:
irb(main):014:0> Band.collection.find(_id: Band.first.id).first
=> {"_id"=>BSON::ObjectId('5de4ba7b026d7c31708db208')}

Verify you are querying the same collection on the same database (e.g. same environment is used in both queries).


text:
Q: Why doesn't MySQL use the primary key on JOIN plus ORDER? Here's a neat one for you (MySQL, obviously):

# Setting things up
DROP DATABASE IF EXISTS index_test_gutza;
CREATE DATABASE index_test_gutza;
USE index_test_gutza;

CREATE TABLE customer_order (
    id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
    invoice MEDIUMINT UNSIGNED NOT NULL DEFAULT 0,
    PRIMARY KEY(id)
);
INSERT INTO customer_order
    (id, invoice)
    VALUES
    (1, 1),
    (2, 2),
    (3, 3),
    (4, 4),
    (5, 5);

CREATE TABLE customer_invoice (
    id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
    invoice_no MEDIUMINT UNSIGNED DEFAULT NULL,
    invoice_pdf LONGBLOB,
    PRIMARY KEY(id)
);
INSERT INTO customer_invoice
    (id, invoice_no)
    VALUES
    (1, 1),
    (2, 2),
    (3, 3),
    (4, 4),
    (5, 5);

# Ok, here's the beef
EXPLAIN
    SELECT co.id
    FROM customer_order AS co;

EXPLAIN
    SELECT co.id
    FROM customer_order AS co
    ORDER BY co.id;

EXPLAIN
    SELECT co.id, ci.invoice_no
    FROM customer_order AS co
    LEFT JOIN customer_invoice AS ci ON ci.id=co.invoice;

EXPLAIN
    SELECT co.id, ci.invoice_no
    FROM customer_order AS co
    LEFT JOIN customer_invoice AS ci ON ci.id=co.invoice
    ORDER BY co.id;

There are four EXPLAIN statements at the bottom. The first two result in exactly what you'd expect:

+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
| id | select_type | table | type  | possible_keys | key     | key_len | ref  | rows | Extra       |
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
|  1 | SIMPLE      | co    | index | NULL          | PRIMARY | 3       | NULL |    5 | Using index |
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+

The third one is already interesting -- notice how the primary key in customer_order is not used any more:

+----+-------------+-------+--------+---------------+---------+---------+-----------------------------+------+-------------+
| id | select_type | table | type   | possible_keys | key     | key_len | ref                         | rows | Extra       |
+----+-------------+-------+--------+---------------+---------+---------+-----------------------------+------+-------------+
|  1 | SIMPLE      | co    | ALL    | NULL          | NULL    | NULL    | NULL                        |    5 |             |
|  1 | SIMPLE      | ci    | eq_ref | PRIMARY       | PRIMARY | 3       | index_test_gutza.co.invoice |    1 | Using index |
+----+-------------+-------+--------+---------------+---------+---------+-----------------------------+------+-------------+

The fourth one, however, is the zinger -- simply adding the ORDER BY on the primary key leads to filesort on customer_order (which is to be expected, given that it was already bewildered above):

+----+-------------+-------+--------+---------------+---------+---------+-----------------------------+------+----------------+
| id | select_type | table | type   | possible_keys | key     | key_len | ref                         | rows | Extra          |
+----+-------------+-------+--------+---------------+---------+---------+-----------------------------+------+----------------+
|  1 | SIMPLE      | co    | ALL    | NULL          | NULL    | NULL    | NULL                        |    5 | Using filesort |
|  1 | SIMPLE      | ci    | eq_ref | PRIMARY       | PRIMARY | 3       | index_test_gutza.co.invoice |    1 | Using index    |
+----+-------------+-------+--------+---------------+---------+---------+-----------------------------+------+----------------+

Filesort! And that while I'm never using anything except the primary key in the customer_order table for ordering, and the primary key in the customer_invoice table for the JOIN. So then, in the name of all that is good and right, why does it switch to filesort all of a sudden?! And more importantly, how do I avoid this? For the record, I will gladly accept a documented answer explaining why this cannot be avoided (if that's the case.)
As you probably suspect by now, this is actually happening in production, and although the tables are by no means huge (only hundreds of records), the filesort on the invoice table (which contains a PDF file) is killing the server when I run queries similar to the one above (which I need in order to know which orders have been issued invoices, and which weren't).
Before you ask, I designed the database, and I thought I was safe storing the PDF files in that table because I never ever need any search queries on it -- I always have its primary key at hand!
Update (comments synopsis)
Here's a synopsis of what was suggested in the comments below, so you don't have to read all of that:

*

**You should add a key on customer_order.invoice* -- I actually tried that in production, it makes no difference (as it shouldn't)

*You should use USE INDEX -- tried that, didn't work. I also tried FORCE INDEX -- no result either (no change whatsoever)

*You oversimplified the use case, we need the actual production query -- I might have stripped it a bit too much in the first iteration, so I updated it (I just added , ci.invoice_no in the SELECT for the last couple of queries). For the record, if anybody's really curious, here's the production query, exactly as it is (this retrieves the last page of orders):

SELECT
    corder.id,
    corder.public_id,
    CONCAT(buyer.fname," ",buyer.lname) AS buyer_name,
    corder.status,
    corder.payment,
    corder.reserved AS R,
    corder.tracking_id!="" as A,
    corder.payment_received as pay_date,
    invoice.invoice_no AS inv,
    invoice.receipt_no AS rec,
    invoice.public AS pub_inv,
    proforma.proforma_no AS prof,
    proforma.public AS pub_pf,
    corder.rating,
    corder.rating_comments!="" AS got_comment
FROM
    corder
LEFT JOIN user as buyer ON buyer.id=corder.buyer
LEFT JOIN invoice as invoice ON invoice.id=corder.invoice
LEFT JOIN invoice as proforma ON proforma.id=corder.proforma
ORDER BY
    id DESC
LIMIT 400, 20;

The query above (which, again, is exactly what I run in production) takes about 14 seconds to run. Here's the simplified query, as shown in the use case above, executed on production:

SELECT
    corder.id,
    invoice.invoice_no
FROM
    corder
LEFT JOIN invoice ON invoice.id=corder.invoice
ORDER BY
    corder.id DESC
LIMIT 400, 20;

This one takes 13 seconds to run. Be advised the LIMIT makes no difference whatsoever as long as we're talking about the last page of results (which we are). That is, there's absolutely no significant difference between retrieving the last 12 results or all 412 results when filesort is involved.
Conclusion
ypercube's answer is not only correct, but unfortunately it seems to be the only legitimate one. I tried to further separate conditions from fields, because the SELECT * FROM corder subquery can end up involving a lot of data, if corder itself contains LONGBLOBs (and duplicating the fields from the main query in the subquery is inelegant), but unfortunately it doesn't seem to work:

SELECT
    corder.id,
    corder.public_id,
    CONCAT(buyer.fname," ",buyer.lname) AS buyer_name,
    corder.status,
    corder.payment,
    corder.reserved AS R,
    corder.tracking_id != "" AS A,
    corder.payment_received AS pay_date,
    invoice.invoice_no AS inv,
    invoice.receipt_no AS rec,
    invoice.public AS pub_inv,
    proforma.proforma_no AS prof,
    proforma.public AS pub_pf,
    corder.rating,
    corder.rating_comments!="" AS got_comment
FROM
    corder
LEFT JOIN user as buyer ON buyer.id = corder.buyer
LEFT JOIN invoice AS invoice ON invoice.id = corder.invoice
LEFT JOIN invoice AS proforma ON proforma.id = corder.proforma
WHERE corder.id IN (
    SELECT id
    FROM corder
    ORDER BY id DESC
    LIMIT 400,20
)
ORDER BY
    corder.id DESC;

This fails, with the following error message:

ERROR 1235 (42000): This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

I'm using MySQL 5.1.61, which is reasonably recent in the 5.1 family (and apparently this is not supported in 5.5.x either).

A: Can you try this version (it basically gets first the 420 rows of the corder table, keeps the 20 of them and then does the 3 outer joins):
SELECT
    corder.id,
    corder.public_id,
    CONCAT(buyer.fname," ",buyer.lname) AS buyer_name,
    corder.status,
    corder.payment,
    corder.reserved AS R,
    corder.tracking_id != "" AS A,
    corder.payment_received AS pay_date,
    invoice.invoice_no AS inv,
    invoice.receipt_no AS rec,
    invoice.public AS pub_inv,
    proforma.proforma_no AS prof,
    proforma.public AS pub_pf,
    corder.rating,
    corder.rating_comments!="" AS got_comment
FROM
    ( SELECT *
      FROM corder
      ORDER BY
        id DESC
      LIMIT 400, 20
    )
    AS corder
LEFT JOIN user as buyer ON buyer.id = corder.buyer
LEFT JOIN invoice AS invoice ON invoice.id = corder.invoice
LEFT JOIN invoice AS proforma ON proforma.id = corder.proforma
ORDER BY
    corder.id DESC ;


text:
Q: Variant of universal algebra where equations are constrained to have a single variable on the right. This question by user107952 asks for equational theories with only infinite models and the trivial model on the set with one element.
There are a few answers such as the ordered-pair theory mentioned in Alex Kruckman's answer:
$$ \pi_1(p(x, y)) \approx x \\ \pi_2(p(x, y)) \approx y \\ p(\pi_1(z), \pi_2(z)) \approx z $$
And the theory of an injective function $s$ mentioned in Noah Schweber's answer, among others.
$$ p(s(x)) \approx x \\ t(0, y, z) \approx y \\ t(s(x), y, z) \approx z $$
And the single theory $(x'y)z \approx y$ .
One thing all of these equations have in common is that the term on the RHS of all of the equations listed is a simple variable.
Let me define the boring algebra on $(\sigma, \lambda)$ where $\sigma$ is a signature and $\lambda$ is an ordinal. Let the domain of the boring $(\sigma, \lambda)$-algebra be $\lambda$. Additionally, let the interpretation of every constant in $\sigma$ be $0$ and let the interpretation of every function in $\lambda$ be the constantly $0$ function.
Let me define a type I equation as having both sides headed by functions or constants, e.g. $1 \approx 0$, $x+1 \approx 0$, etc. A type II equation has one term headed by a function and one term headed by a variable like the examples above. A type III equation has two variables, it is equivalent to $x \approx x$ or $x \approx y$ neither of which are interesting.
Some axioms like associativity are type I $(a + b) + c \approx a + (b + c)$. However, any theory in $\sigma$ with only type I axioms will have every boring algebra in $\sigma$ as a model.
My question is: do we get an interesting subset of universal algebra if we restrict our attention to type II equations?

A: Let me say something about Type II identities.
These are the identities of the form $w\approx x$
where $x$ is a variable and $w=s(t_1,\ldots,t_n)$
where $s$ is a function symbol and each $t_i$ is a term
in a set $V$ of variables.
I will call the function symbol $s$ the outermost
function symbol on the LHS.

I take the question to be: Let $L$ be an algebraic language.
What can be said about an equational theory $\Sigma$
in the language $L$ if $\Sigma$ has a set
of axioms consisting of Type II identities?
I don't know the full answer, but I will make a few comments.
Observation.
An equational theory $\Sigma$ contains a
Type II identity $s(t_1,\ldots,t_n)\approx x$,
for a particular choice of the outermost function symbol $s$,
if and only if
$s$ interprets as a surjective function
in every model of $\Sigma$.

Only if. Assume that $\Sigma$ contains
$s(t_1,\ldots,t_n)\approx x$ and $M$ is a model of $\Sigma$.
We must show that $s^M\colon M^n\to M$ is a surjective function.
Choose $m\in M$ arbitrarily, let $v$ be any valuation
$v\colon V\to M$ such that $v(x)=m$.
Since $M\models s(t_1,\ldots,t_n)\approx x$, we have
$s^M(t_1[v],\ldots,t_n[v]) = x[v] = v(x) =m$, so $m$
is in the image of $s^M$. $\Box$

If.
Assume $s$ is surjective on all models of $\Sigma$.
Let $F = F_{\Sigma}(x)$ be the free $\Sigma$-algebra
over the set $\{x\}$.
Since $s^F\colon F^n\to F$ is surjective, there is
an $n$-tuple $(t_1,\ldots,t_n)\in F^n$ such that
$s^F(t_1,\ldots,t_n)=x\in F$. This relation
satisfied by the free generator $x\in F$
must hold universally in all models of $\Sigma$
by the universal mapping property for free algebras, so all
models of $\Sigma$ satisfy $s(t_1,\ldots,t_n)\approx x$. $\Box$

The above observation makes it clear that if
${\bf A}$ is an algebra that has no surjective
fundamental operations, then ${\bf A}$ does not satisfy
any Type II identities. This is enough to conclude that
some equational theories do not have axioms consisting
of Type II identities.
Groups have surjective multiplication
$\ast\colon G\times G\to G$ and surjective inverse
${}^{-1}\colon G\to G$,
raising the question of whether the theory of groups
can be axiomatized by Type II identities.
The answer is Yes. An old result about this is in

A. Tarski.
Ein Beitrag zur Axiomatik der Abelschen Gruppen.
Fundamenta Mathematicae, 30:253-256, 1938.
Tarski proves that the class of abelian groups
can be axiomatized in the language of division
$x/y: = x-y$ by the Type II identity
$$
x / (y / (z / (x / y))) \approx z.
$$
Higman and Neumann proved in
G. Higman and B. H. Neumann.
Groups as groupoids with one law.
Publicationes Mathematicae Debrecen, 2:215-227, 1952.
that the class of all (not necessarily abelian)
groups can also be axiomatized in the language of division
by the Type II identity
$$
x / ((((x / x) / y) / z) / (((x / x) / x) / z)) \approx y.
$$
Kunen proved in
K. Kunen.
Single axioms for groups.
J. Automated Reasoning, 9(3):291-308, 1992.
that the class of all groups can be axiomatized in the language
of multiplication and inverse by the Type II identity
$$
 ((z * (x * y)')' * (z * y')) * (y' * y)' \approx x.
$$
McCune proved in
W. McCune
Single axioms for Boolean algebra
Mathematics and Computer Science Division
Technical Memorandum No. 243, June 2000
that the class of Boolean algebras expressed in the language
of NOR (Sheffer stroke) is axiomatized by the Type II identity
$$(((((x|(((y |z )|(y |(u|z )))|y ))|y )|(((y |z )|(y |(u|z )))|(x|(y |
y ))))|((((v |(v |w ))|w )|(v |(v |(w |w ))))|y ))|y )|((((v |(v |w ))|
w )|(v |(v |(w |w ))))|((((x|(((y |z )|(y |(u|z )))|y ))|y )|(((y |
z )|(y |(u|z )))|(x|(y |y ))))|(y |y ))) \approx w.$$

All of the above results seem to focus on theories axiomatized
by a single Type II identity.
There is an interesting result that connects
theories axiomatized by finitely
many Type II identities with theories axiomatized by
a single Type II identity in
R. McKenzie
Equational bases for lattice theories.
Mathematica Scandinavica, Vol. 27, No. 1 (1970), pp. 24-38.
Theorem 1.2.
(paraphrased)
If $\Sigma$ is an equational theory that can be axiomatized
by finitely many Type II identities,
and $\Sigma$ contains the near unanimity identities for some term
$m(x_1,\ldots,x_k)$, then $\Sigma$ can be axiomatized
by a single Type II identity.
(The near unanimity identities for $m$ are
$m(y,x,x,\ldots,x)$ = $m(x,y,x,\ldots,x)$ = $\cdots$ = $m(x,x,x,\ldots,y)$ = $x$.)


text:
Q: android what is the event after invoking third party application? I'm kinda new to android, i just wanna ask android what is the event after invoking third party application?
for example i have the following code to open the adobe reader to read my file from the sdcard:
File fileToShow = new File(passedFileToShow);
Intent nextActivity = new Intent();
nextActivity.setAction(android.content.Intent.ACTION_VIEW);
nextActivity.setDataAndType(Uri.fromFile(fileToShow), "application/pdf");
nextActivity.putExtra("itemName", itemName );
startActivityForResult(nextActivity, 0);

after opening the adobe reader and i finished reading the file, how do i call the event after i tap the device back button?
onBackPressed doesn't work,
onActivityResult doesn't work too..
thanks a lot for any help! :)

A: if you pressed the back button, it's going to call onRestart (Also it should call onActivityResult with the resutlCode *Activity.RESULT_CANCELED*)
You can see the whole activity lifecyle here

A: What I would do is define a boolean which keeps track of if the user opened adobe.
 boolean userOpenedAdobe = false;

Then set it to true just prior to opening the pdf:
File fileToShow = new File(passedFileToShow);
Intent nextActivity = new Intent();
nextActivity.setAction(android.content.Intent.ACTION_VIEW);
nextActivity.setDataAndType(Uri.fromFile(fileToShow), "application/pdf");
nextActivity.putExtra("itemName", itemName );
userOpenedAdobe = true;
startActivityForResult(nextActivity, 0);

Then you can check the boolean in the onResume() and do something.  Just remember to set it back to false afterward:
protected void onResume() {
    super.onResume();
    if (userOpenedAdobe) {
        // do something
    }
    userOpenedAdobe = false;
}


text:
Q: Correct manner in implementing a tables header view using Swift and UITableView I'm a junior iOS developer and I'm playing around with a UITableView. As the title suggests, I'm looking for the correct way to insert a given view into the header section of a UITableView. I've used the following two methods:
tableView.tableHeaderView = NSBundle.mainBundle().loadNibNamed("InputToListCell", owner: nil, options: nil)[0] as! UITableViewCell

and
let nib = UINib(nibName: "InputToListCell", bundle: nil)
tableView.registerNib(nib, forHeaderFooterViewReuseIdentifier:"InputToListCell")

override func tableView(tableView:UITableView, viewForHeaderInSection section:NSInteger) -> UIView{
    let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier("InputToListCell")
    return header!;
}

Which would be the better method? If there is even a better method as both of them work or is this a matter of preference? I'm just wondering why have two things that do the same thing? For flexibility?

A: They do different things.
Your first block will add a tableHeaderView  A single view that appears over the whole table and scrolls with the table.
The second block will create a section header that will be displayed at the top of each section in the table.  It will mostly scroll with the table, but it will pin to the top of the screen until the whole section has been scrolled off screen.
So, it all depends on which you're actually trying to do.  In a table without sections (technically with only one section), they are very similar with the difference being that the second will pin to the top of the screen, but the first will not.
BTW, in both cases, the tableHeaderView need not (probably shouldn't be) derived from UITableViewCell


text:
Q: Word Wheel Game - randomising letters with Javascript Thanks Adrian for sharing some code with me. Unfortunately I was unable to integrate it into my project (newbie!) but it did put me on the correct course. After a bit of a rethink, I included a function to shuffle the letters to rather a nice effect. Only problem is my code does not work outside the realm of CodePen. I think some errors have crept in from my Frankenstein approach to coding! Anyway, I'm so close, can anyone help or is it just too disorganise to bother with?
//GET RANDOM 9 LETTER WORD

var wordlist = ["aardvarks", "aasvogels", "abamperes", "abandoned"
];

var randomNumber = parseInt(Math.random() * wordlist.length);
var name = wordlist[randomNumber];

if(document.getElementById("resultRandomWord")){
document.getElementById("placeholderRandomWord").removeChild(document.getElementById("resultRandomWord"));
}
var element = document.createElement("div");
element.setAttribute("id", "resultRandomWord");
element.appendChild(document.createTextNode(name));
document.getElementById("placeholderRandomWord").appendChild(element);

//START This function shuffles list items
(function($){
$.fn.shuffle = function() {
    return this.each(function(){
        var items = $(this).children().clone(true);
        return (items.length) ? $(this).html($.shuffle(items)) : this;
    });
}

$.shuffle = function(arr) {
    for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
    return arr;
}
})(jQuery);
//END This function shuffles list items

//SPLIT 9 LETTER WORD
var str = $('#resultRandomWord').html();
var spl = str.split('');
var len = spl.length;
var i = 0;
setInterval(function(){

if(i < len)
{
    if(spl[i] != " "){
    $('.letters').append('
'+spl[i]+'
')//DISPLAY WORD AS SEPARATE LETTER AND AS LIST ITEMS
    $('.letters').shuffle();//Call shuffle function
    }
}
i++;
},200)

//REVEAL ANSWER (JQUERY)
$(document).ready(function(){
$(".reveal").click(function(){
$("#placeholderRandomWord").slideToggle();
   });
});

And HTML:

<button type="button" class="reveal" onclick>Reveal/Hide Answer</button>

A: Normally I'd ask to see your own attempt, but you've made a lot of progress on the rest and it looks like this is just a minor stumbling block. So, it's not tested to destruction, but the following function should do what you need:
function randomise(word) {
    var result = "";
    while (word != "") {
        var pos =  Math.floor(Math.random () * word.length);
        result += word[pos];
        word = word.substring(0, pos) + word.substring(pos+1);
    }
    return result;
}

It simply chooses a random number between 0 and (length of word - 1), picks out that letter and removes it from the original word, then repeats until the original word is empty.


text:
Q: python - Class attributes apparently not inherited In a recent project I try to do something like this (more complex, but the same result):
class MetaA(type):
    def __new__(cls, name, args, kwargs):
        print kwargs["foo"]
        return type.__new__(cls, name, args, kwargs)

class A(object):
    __metaclass__ = MetaA
    foo = "bar"

class B(A):
    pass

I get this:
bar
Traceback (most recent call last):
  File "C:\Users\Thorstein\Desktop\test.py", line 10, in <module>
    class B(A):
  File "C:\Users\Thorstein\Desktop\test.py", line 3, in __new__
    print kwargs["foo"]
KeyError: 'foo'

Are class attributes not inherited? If so, is there any workaround possible in a similar framework to the above?
EDIT:
Might be easier to see what I mean using an actual (simplified) example from the program..
class GameObjectMeta(type):
    def __new__(cls, name, bases, attrs):
        attrs["dark_color"] = darken(*attrs["color"])
        return type.__new__(cls, name, bases, attrs)

class GameObject(object):
    __metaclass__ = GameObjectMeta
    color = (255,255,255)   # RGB tuple

class Monster(GameObject):
    pass

Basically, want to run a function on the base color to make a darker one that's saved in the class (multiple instances of the class will want the same color, but there will be a longer class hierarchy). I hope this'll make more sense..

A: It's not supposed to inherit those.  The metaclass receives the attributes defined on the class it is instantiating, not those of its base classes.  The whole point of the metaclass constructor is to get access to what is actually given in the class body.
In fact, the attributes of the base class really aren't "in" the subclass at all.  It's not as if they are "copied" to the subclass when you define it, and in fact at creation time the subclass doesn't even "know" what attributes its superclasses might have.  Rather, when you access B.foo, Python first tries to find the attribute on B, then if it doesn't find it, looks on its superclasses.  This happens dynamically every time you try to read such an attribute.  The metaclass mechanism isn't supposed to have access to attributes of the superclass, because those really aren't there on the subclass.
A perhaps related problem is that your definition of __new__ is incorrect.  The arguments to the metaclass __new__ are cls, name, bases, and attrs.  The third argument is the list of base classes, not "args" (whatever you intend that to be).  The fourth argument is the list of attributes define in the class body.  If you want access to inherited attributes you can get at them via the bases.
Anyway, what are you trying to accomplish with this scheme?  There's probably a better way to do it.

A: If you use the __init__ instead of __new__ then you can inherit the base class attributes:
class MetaA(type):
    def __init__(self, name, bases, attr):
        print self.foo  # don't use attr because foo only exists for A not B
        print attr  # here is the proof that class creation does not follow base class attributes
        super(MetaA, self).__init__(name, base, attr)  # this line calls type(), but has no effect

class A(object):
    __metaclass__ = MetaA
    foo = 'bar'

class B(A):
    pass

when A is created returns:
bar
{'__module__': '__main__', 'foo': 'bar', '__metaclass__': <class '__main__.MetaA'>}

when B is created returns:
bar
{'__module__': '__main__'}

Note, and this is what @BrenBarn was saying in his answer, that foo is not in attr when B is created. That's why the code in OP question raises KeyError. However calling self.foo looks for foo in B then if it can't find it looks in its bases, IE A.
The metaclass for both classes can be determined by looking at its class:
>>> print A.__class__
<class '__main__.MetaA'>
>>> print A.__class__
<class '__main__.MetaA'>

The fact that the metaclass __init__ method is called when allocating and initializing B, printing self.foo and attr in stdout also proves that B's meta class is MetaA.


text:
Q: What is a Valid Trust Anchor in Windows 7 relating to Wifi? The error below just started happening at work with a personal laptop running Windows 7 Ultimate. I'm unable to use installed, non-expired certificates to connect to a private wireless network. No recent changes were made by IT that would explain the issue. It worked fine several weeks ago and happens on two laptops I own.
The details and some screen shots are available here:

The error we don't understand is this:

The credentials provided by the server
  could not be validated. We recommend
  that you terminate the connection and
  contact your administrator with the
  information provided in the details.
  You may still connect but doing so
  exposes you to the security risk by a
  possible rogue server.
The server XYZ presented a valid
  certificate issued by Company Name
  Certificate Authority but Company Name
  Certificate Authority is not
  configured as a valid trust anchor for
  this profile.

We don't know to to resolve the issue without ignoring the error (nor what's changed that could explain this new error).
The new information is that we have our own Root CA, and that the certificates were not updated recently, nor have any expired.

A: I ran across the same issue.  Found the answer.

*

*Go to Control Panel > Network and Internet > Manage Wireless Networks.

*Open the wireless network.  Or, click the "Add" button to create a new network, then open it.

*The Wireless Network Properties window appears.  Click the Security tab.

*Under "Choose a network authentication method", select "Microsoft: Smart Card or other certificate".  I assume this is already selected.

*Click the "Settings" button.

*The "Smart Card or other Certificate Properties" window appears.

*Here is the answer.  Under the "Trusted Root Certification Authorities" list, you have to manually select the Root CA of your company.  By default, these are all blank.  That is why the warning message appears the first time if you do not select your company's Root CA.  If you connect despite the warning, then your company's Root CA is now selected, and you no longer get the warning on subsequent connections.  So, to avoid the warning, just select this box when you set up the network, before you connect for the first time.

*If you do not see your company's Root CA here, that is likely due to the fact that by default, double clicking your certificate to install it probably puts it under the "Intermediate Certification Authorities" tab.  You need to select the "Trusted Root Certification Authorities" tab instead.  You can see where certificates go under: Internet Explorer > Internet Options > Content > Certificates

A: The way an SSL certificate is authenticated as valid is by following a chain of trust. Whatever cert that your company is using to secure wifi is then validated against (at least) one intermediate certificate that verifies that it is legit. That intermediate certificate is, in turn, authenticated against a root certificate from a verified and trusted company.
The way the root certificates are validated as authentic and can be trusted is that Microsoft builds trust into Windows for certain certs, but these roots are usually outdated and don't have some major players in the SSL cert game. Verisign and Thawt usually have no problems, but Digicert (Entrust.net) is a huge SSL cert company that isn't natively trusted by Windows for 802.1x (which I'm assuming your wifi is using to authenticate based on the screen shots provided). This means that the cert is probably valid, but your computer doesn't know to trust it. You can certainly import that root cert as a trusted cert so that you aren't prompted with this any more. I would contact your system administrator about how to do that.
This could be caused by either the expiration of an intermediate or root cert if your company uses their own CA, or by them issuing a new root cert and not deploying it to you.

A: I got to exactly the same point.  If I accept the certificate warning, a userid / password prompt appears.  If I enter my userid (the common name of the client cert - I shouldn't have to enter it), and leave the password blank, I successfully connect. Pretty weird and not how it was before.
Edit.  All sorted.  I had manually entered a wireless network profile, and used a lower case name whereas the corporate wireless starts with an uppercase letter.  My successful connection mentioned earlier was not using my manually created profile at all.  Once I defined a correclty named profile, it all worked as it used to.


text:
Q: How to test NSPersistentDocument in XCTestCase? I'm just starting an OS X document-based app using Core Data. To test my model relationships, I'd like to create some NSManagedObject entities, save them to a file, and read them back in an XCTestCase object. Using code like below, I can create entities in the managed object context, but I cannot figure out how to create a functioning persistent store coordinator and/or save to a file.
class MyTests: XCTestCase {

    var doc: Document!
    var moc: NSManagedObjectContext!
    //...//

    override func setUp() {
        super.setUp()
        doc = Document()
        moc = doc.managedObjectContext
    }

    //...//
}

A: Problem with my initial approach above was that I was getting the managedObjectContext before using configurePersistentStoreCoordinatorForURL. Once I resolved that, the solution was fairly straightforward.
class DocTests : XCTestCase {

    let testFileURL = NSURL.fileURLWithPath("/Users/Me/Temp/DocTests", isDirectory: false)

    override func setUp() {
        super.setUp()
    }

    func testWriteAndRead() {

        writeSimpleTestDocument()

        let doc = Document()
        do {
            try doc.readFromURL(testFileURL, ofType: "mydoctype")
        } catch let error as NSError {
            print("Failed to read, \(error), \(error.userInfo)")
        }

        let moc = doc.managedObjectContext!

        // fetch from moc and verify test entities here ...
        // ...
    }

    func writeSimpleTestDocument() {

        // if test document exists, delete it
        let fm = NSFileManager.defaultManager()

        if fm.fileExistsAtPath(testFileURL.path!) {
            do {
                try fm.removeItemAtURL(testFileURL)
            } catch let error as NSError {
                print("Failed to remove, \(error), \(error.userInfo)")
            }
        }

        let doc = Document()

        do {
            try doc.configurePersistentStoreCoordinatorForURL(testFileURL, ofType: "mydoctype", modelConfiguration: nil, storeOptions: nil)
        } catch let error as NSError {
            print("Failed to configure coordinator, \(error), \(error.userInfo)")
        }

        let moc = doc.managedObjectContext!

        // create test entities in moc here ...
        // ...

        do {
            try moc.save()
        } catch let error as NSError {
            print("Failed to save, \(error), \(error.userInfo)")
        }
    }

}


text:
Q: Stop Firebug from consolidating css attributes Using Firebug 1.5.4. When I am inspecting an element, Firebug converts declaration "padding: 10px 0 13px 0" to "padding: 10px 0 13px" in the inspection window, which bugs me. Yet it leaves "margin: 0 0 0 16px;" as is which I like. (How come it didn't consolidate that one?)
Is there a setting in Firebug to show all css attributes in expanded (none consolidated) format?

A: You can easily verify that Firebug is not consolidating as you think it is. Just edit an elements Style using Firebug > HTML > Style > New Property  and use
padding: 2px 3px 4px 0;

You will see that Firebug does not remove the trailing 0;
My guess is that Firefox chooses not to report a zero value for the trailing values in a shorthand property.  Firebug is just showing you the result.

A: This annoys me too!   Worse, it does it semi-randomly.
For example, 2px 3px 4px 0 doesn't seem to get clipped but 10px 0 13px 0 usually does.
I haven't found any kind of setting, but one work-around is to always specify units.
10px 0 13px 0px gets rewritten to 10px 0 13px 0, which is acceptable.
.
Another workaround is to check the Expand Shorthand Properties menu item.  But, this breaks "padding" into "padding-left",  "padding-top", etc.


text:
Q: can't access NAS after 16.04 LTS upgrade I have a WD My Cloud NAS which I've been using for several years through Nautilus using a location bookmark (smb://000.000.0.000, not all zeros of course but the ip of the device). I have smbclient installed (but not Samba itself) and all was well until the 16.04 LTS upgrade.
Now, I cannot connect to the NAS at all - no error messages, just no connection.
I originally assumed this was due to a Samba bug (and on Launchpad there are a few) but now I'm not so sure because I can't connect using Gigolo either (which uses GVFS for network connections, an entirely different method than Samba).
So far I've reinstalled smbclient, gigolo, gvfs-fuse, restarted the computer and recreated my Nautilus bookmark (several times) all with no good result.
I don't have a great deal of Linux experience and am hoping someone here can help me solve this issue.

A: https://bugs.launchpad.net/ubuntu/+source/gvfs/+bug/1409032
provides the info re: this problem and post #29 has a workaround that solved it for me.


text:
Q: Cocos2D - CCSprite touched followed by popup I've been stumped for days trying to get my sprite touch method under control. My aim is to have another sprite pop up offset to a touched sprite.
I currently have a half baked code for this process, in which I have experimented with many varieties of code, see links below, none of which has worked. My questions:

*

*Getting CCTouchBegan to run the method towerPositionTapped once the touch hits a sprite on screen (the NSLog in CCTouchBegan is also not working).

*Find out how to get the location of the touched sprite so that it can be used in the towerPositionTapped method.

My touch specific code so far in the main layer:
-(void) registerWithTouchDispatcher{
[[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0
    swallowsTouches:YES];
}

-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{

CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL: location];

//_towersFromClass is an NSMutableArray with CCSprite objects
for(CCSprite *tb in _towersFromClass){
    if(CGRectContainsPoint(tb.boundingBox,location)){

        NSLog(@"sprite touched at %@", NSStringFromCGPoint(location));

        [self towerPositionTapped]

        return YES;
    }
}
return NO;
}

The NSLog check doesn't end up showing when I click on any of the sprites.
For the towerPositionTapped method I am unsure how to capture the touched location (or record the touched sprite) in order to position the new sprite.
towerPositionTapped.m
-(void)towerPositionTapped{

CCMenuItem *towerOption1 = [CCMenuItemImage itemWithNormalImage:@"tower.png" selectedImage:@"tower.png"];
towerOption1.position = /* place touched sprite location here, with an offset*/;

CCMenu *_towerOptionsMenu = [CCMenu menuWithItems: nil];
_towerOptionsMenu.position = CGPointZero;
[self addChild:_towerOptionsMenu z:5];

}
Any constructive criticism is appreciated. Thank you for your time.
A few of the sites I have been testing:
Sprite Offset
Touch 1
Touch 2

A: If you CCTouchBegin in not working ( not inside for loop but overall) Then may be you have to try this line if you havnt EnableTouch
self.isTouchEnabled = YES;

I am using this line rather than registerWithTouchDispatcher.

A: It's taken me a few days to solve this, none the less I have managed to come up with a solution.
I've basically used the same code as in Ray Wenderlich's Tower Defence Tutorial (RWTDTutorial). Using the CCTouchesBegan method.
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

for(UITouch *touch in touches){
    CGPoint location = [touch locationInView:[touch view]];

    location = [[CCDirector sharedDirector] convertToGL:location];

    for(CCSprite *tb in _towersFromClass){

        if(CGRectContainsPoint([tb boundingBox],location)){

            selectedTowerPosition = tb;
            [self towerPositionTapped];

        }
    }
}
}

I created another method which contains the CCMenu items I wanted to pop up after I selected one of the CCSprites in my _towersFromClass array, and added that under the 'if' statement of the CCTouchesBegan method.
In order to get the correct location for the menu, I created a CCSprite property '_selectedTowerPosition' and made it = the for 'tb' CCSprite.
Back in the CCMenu method I used the ccpAdd code, as seen below, to position the menu.
CCMenuItem *towerOption1 = [CCMenuItemImage itemWithNormalImage:@"tower.png" selectedImage:@"tower.png" target:self selector:@selector( towerSelectOption)];
towerOption1.position = ccpAdd(_selectedTowerPosition.position,ccp(40,0));

I also gave the menu item a slight offset.
It's taken me awhile but I've learned a lot from this experience.


text:
Q: document.querySelector() is not applying style Could someone point my mistake
here ?

  This is dummy content

angular.module("app", [])

  .controller("demo", function($scope) {
    $scope.p = document.querySelector('.bgColor');

    var styles = {
      'background-color': 'red'
    };
    Object.assign($scope.p.style, styles);
  });

I'm trying to modify the class the property but am actually getting TypeError: Cannot read property 'style' of null in my Angular.js 1.x application. But when try in fiddle, I couldn't see the error but also style is not applied.
Thanks every one

A: Please see the following working snippet. Also keep in mind that AngularJS documentation discourages using controllers to manipulate the DOM.

angular.module("app", [])

  .controller("demo", function($scope) {
    $scope.p = document.querySelector('.bgColor');

    Object.assign($scope.p.style, {
      'background-color': 'red'
    });
  });

  This is dummy content

A: You aren't accessing the element at the right time it seems. This is why it says "null".
var p = document.querySelector('.bgColor');
var styles = {
      'background-color': 'red'
    };
console.dir(p);
Object.assign(p.style, styles);

Putting this code after the controller part does work for me in chrome.


text:
Q: Problems with inline django modelformset? I am learning to implement django inlineformset and I am facing the following error. On the client side, I am using the  django-dynamic-formset jquery plugin. But when I render the formset, I see 'add another or remove option appear multiple times. This is what I tried so far.This error happened when I switched to formset in the instead of form.
forms.py:
class BaseSkillFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        super(BaseSkillFormSet, self).__init__(*args, **kwargs)
        self.queryset = Skill.objects.exclude(skill_name__isnull=True)

class BaseWorkExperienceFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        super(BaseWorkExperienceFormSet, self).__init__(*args, **kwargs)
        self.queryset = WorkExperience.objects.exclude(
            company_name__isnull=True)

class BaseEducationFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        super(BaseEducationFormSet, self).__init__(*args, **kwargs)
        self.queryset = Education.objects.exclude(name__isnull=True)

class SkillForm(forms.ModelForm):
    class Meta:
        model = Skill
        fields = ('skill_name', 'level_of_proficiency',)

class WorkExperienceForm(forms.ModelForm):
    class Meta:
        model = WorkExperience
        exclude = ('user',)
        widgets = {
            'start_date': DateInput()
        }

class EducationForm(forms.ModelForm):
    class Meta:
        model = Education
        exclude = ('user',)
        widgets = {
            'start_date': DateInput()
        }

class CollectionCreate(UpdateView):
    model = UserProfile
    template_name = 'accounts/user_profile_form.html'
    form_class = UserProfileForm
    success_url = None

    def get_context_data(self, **kwargs):

        data = super(CollectionCreate, self).get_context_data(**kwargs)
        if self.request.POST:
            data['formset'] = SkillFormSet(self.request.POST)
            data['formset1'] = WorkExperienceFormSet(self.request.POST)
            data['formset3'] = EducationFormSet(self.request.POST)

            return data
        else:
            print('object', self.object)
            data['formset'] = SkillFormSet()
            data['formset1'] = WorkExperienceFormSet()
            data['formset3'] = EducationFormSet(instance=self.object)
            return data

SkillFormSet = inlineformset_factory(
    UserProfile, Skill, formset=BaseSkillFormSet,
    fields=['skill_name', 'level_of_proficiency'], can_delete=True, extra=1
)

WorkExperienceFormSet = inlineformset_factory(
    UserProfile, WorkExperience, formset=BaseWorkExperienceFormSet,
    fields=['company_name', 'start_date', 'end_date', 'work_description'],
    can_delete=True, extra=1,
)

EducationFormSet = inlineformset_factory(
    UserProfile, Education, formset=BaseEducationFormSet,
    fields=['name', 'start_date', 'end_date', 'education_type'],
    can_delete=True, extra=1, max_num=5,
)

formset.html
    {% load static %}
    {% load crispy_forms_tags %}

    {{ formset.management_form|crispy }}

        {% for form in formset.forms %}

                    {% for field in form.visible_fields %}

                        {# Include the hidden fields in the form #}
                        {% if forloop.first %}
                            {% for hidden in form.hidden_fields %}
                                {{ hidden }}
                            {% endfor %}
                        {% endif %}
                        {{ field.errors.as_ul }}
    {{ field|as_crispy_field }}

                    {% endfor %}

        {% endfor %}

    {% for form in formset1.forms %}

                    {% for field in form.visible_fields %}

                        {# Include the hidden fields in the form #}
                        {% if forloop.first %}
                            {% for hidden in form.hidden_fields %}
                                {{ hidden }}
                            {% endfor %}
                        {% endif %}
                        {{ field.errors.as_ul }}
    {{ field|as_crispy_field }}

                    {% endfor %}

        {% endfor %}

    {% for form in formset2.forms %}

                    {% for field in form.visible_fields %}

                        {# Include the hidden fields in the form #}
                        {% if forloop.first %}
                            {% for hidden in form.hidden_fields %}
                                {{ hidden }}
                            {% endfor %}
                        {% endif %}
                        {{ field.errors.as_ul }}
    {{ field|as_crispy_field }}

                    {% endfor %}

        {% endfor %}

A: You need to instantiate each formset separately.
Use a separate table for each formset, add a unique ID and use it to instantiate the formset, something like this:
{% load static %}
{% load crispy_forms_tags %}

{{ formset.management_form|crispy }}

    {% for form in formset.forms %}

                {% for field in form.visible_fields %}

                    {# Include the hidden fields in the form #}
                    {% if forloop.first %}
                        {% for hidden in form.hidden_fields %}
                            {{ hidden }}
                        {% endfor %}
                    {% endif %}
                    {{ field.errors.as_ul }}
                    {{ field|as_crispy_field }}

                {% endfor %}

    {% endfor %}

{% for form in formset1.forms %}

                {% for field in form.visible_fields %}

                    {# Include the hidden fields in the form #}
                    {% if forloop.first %}
                        {% for hidden in form.hidden_fields %}
                            {{ hidden }}
                        {% endfor %}
                    {% endif %}
                    {{ field.errors.as_ul }}
                    {{ field|as_crispy_field }}

                {% endfor %}

    {% endfor %}

{% for form in formset2.forms %}

                {% for field in form.visible_fields %}

                    {# Include the hidden fields in the form #}
                    {% if forloop.first %}
                        {% for hidden in form.hidden_fields %}
                            {{ hidden }}
                        {% endfor %}
                    {% endif %}
                    {{ field.errors.as_ul }}
                    {{ field|as_crispy_field }}

                {% endfor %}

    {% endfor %}


text:
Q: Send long string (Base64 encoded image) via HttpGet I'm trying to send an image as a Base64 encoded string to my PHP script via HttpGet, but as I kind of expected I get a 414 URI too large from my server.
Is there a way to post large strings with HttpGet?
Any help is greatly appreciated.

A: URI limit depends on server settings and its not a good idea to send huge data via Get method. And no, you cant use Post on Get service.
The best would be to alter your webservice to receive Post request and then you may send as long data as you want

A: when the URI is too large (cause of you are using it to send an image...) all you can do is to try to make it smaller, by compressing it. Or if you have access to the server, increase the limit....
the one way or the other.... use http-post instead of http-get.
you wont have the problem that the size is limited (or if theres a limit, its way bigger then the one from http-get) and i cant believe that sending an image via http-get is usage as intended by the http


text:
Q: Positive definite Hermitian matrices of countable rank Say that a $\omega\times \omega$ Hermitian matrix $A$ is positive semidefinite of rank $n$ if there exists a $\omega\times n$ complex matrix $B$ such that $A=B B^\dagger$ where $^\dagger$ denotes the conjugate transpose.
Let $f$ be a real-analytic function that converges in a neighbourhood of the origin in ${\mathbb{C}}$. Develop $f=\sum_{i,j=0}^\infty c_{ij} z^i\bar{z}^j$ as a power series in $z$ and $\bar{z}$. Suppose that $f$ is real-valued so that $(c_{ij})$ is a $\omega\times \omega$ Hermitian matrix.
Suppose one shows that for any $(a_k)\in l^2({\mathbb{C}})$, the sum $\sum_{i,j=0}^\infty c_{ij} a_i\bar{a_j}$ is nonnegative. Does this imply that $(c_{ij})$ is positive semidefinite of some rank $n\le \omega$?
This characterization of positive semidefiniteness is valid for finite rank Hermitian matrix. But I'm unsure about the convergence conditions in the infinite rank case.

A: I'm puzzled as to why you would expect this ... no, let $(c_{ij})$ be the identity matrix ($c_{ii} = 1$, $c_{ij} = 0$ for $i \neq j$). That is positive semidefinite but it has infinite rank.
There's a well-developed theory of positive semidefiniteness for operators on $l^2$. If the operator is bounded, then $\langle Av,v\rangle \geq 0$ for all $v \in l^2$ does imply that
$A = B^*B$ for some bounded operator $B$.
Edit: I just noticed that you asked for "rank $n \leq \omega$".  If you weren't conjecturing finite rank, the question makes more sense. But if $n$ could equal $\omega$, then without boundedness assumptions expressions like $B^*B$ don't make sense.
So I think the answer I wrote above that ignores the red herring of "rank" may be what you want.  If you're really interested in unbounded operators we can talk about them too.


text:
Q: html set title attribute to display line break How can I display line-breaks for a hover event using title on a simple html-element? / What is the proper code to be used?
I am trying to set the title attribute like so:
.setAttribute('title', 'line1 &#013; \
-  /n \/n /r line2')

..That does not work. Is does not break anywhere.

....................

--- Code sample ---

const box = document.querySelector('.box');

// set `id` attribute on element
box.setAttribute('title', 'line1

-  /n \/n /r line2');

this works with "&#013;"

A: You were close, but used a slash instead of a backslash in \n. HTML code, on the other hand, will not get parsed, so
 or entities will not work from JavaScript.
From the HTML Standard:

If the title attribute's value contains U+000A LINE FEED (LF) characters, the content is split into multiple lines. Each U+000A LINE FEED (LF) character represents a line break.

As per JavaScript Escape sequences, \n maps to that character.
You also can add unicode characters to a string like this:
box.setAttribute('title', "line1\u{000A}line2");

Plus, instead of using a regular string as the attribute value, you can use a template literal, which allow you to add line breaks to the string:
box.setAttribute('title', `line1
line2`);

Please beware the following remark from the HTML specification. You should not rely on the title attribute to provide information that is not provided by other means.

Relying on the title attribute is currently discouraged as many user agents do not expose the attribute in an accessible manner as required by this specification (e.g., requiring a pointing device such as a mouse to cause a tooltip to appear, which excludes keyboard-only users and touch-only users, such as anyone with a modern phone or tablet).

// set by means of Unicode
document.querySelector('.box1').setAttribute('title', "line1\u{000A}line2");

// set `title` attribute on element by means of template literal
document.querySelector('.box2').setAttribute('title', `line1
line2`);

// simple with \n
document.querySelector('.box3').setAttribute('title', `line1\nline2`);


text:
Q: How do i colour the max value on a plot() in R? plot(1:4,dbinom(1:4,4,0.7),
     type='h',
     main='Binominal Distribution (n=4, p=0.7',
     ylab='Probability',
     xlab='# Successes',
     lwd=3,xaxt="n")

This is my plot and i want to colour only the highest bar,  but i don´t know how to associate the max() to the col = " "

A: This should work:
y <- dbinom(1:4,4,0.7)
plot(1:4,y,
     type='h',
     col = ifelse(y == max(y), "red", "black"),
     main='Binominal Distribution (n=4, p=0.7',
     ylab='Probability',
     xlab='# Successes',
     lwd=3,xaxt="n")


text:
Q: how to use box2d b2Distance function i know b2Distance is used to compute two shape's distance,but how to use it? i don't know how to set the parameters of b2Distance(),e.g this is the structure of b2DistanceInput ,
public class b2DistanceInput
{
                public var proxyA:b2DistanceProxy;
                public var proxyB:b2DistanceProxy;
                public var transformA:b2Transform;
                public var transformB:b2Transform;
                public var useRadii:Boolean;
}

does anybody can tell me what's b2DistanceProxy?what's useRadii,if you can give me an example,it will help to a lot,thanks

A: Just pass the 2 bodies position on b2Distance parameters:
float distance = b2Distance(body1->GetPosition(), body2->GetPosition());


text:
Q: Calculate Euclidean distance between two points in a pandas dataframe My data in a pandas dataframe looks like this:
Sample  Point   Axis  Value1    Value2

S1       P1      X     1.2       1.28
S1       P1      Y     3.4       3.6
S1       P1      Z     1.4       1.6
S1       P2      X     1.2       1.23
S1       P2      Y     -3.4      -3.5
S1       P2      Z     1.4       1.48
S1       P3      X     1.65      1.68
S1       P3      Y     0.8       0.96
S1       P3      Z     2.0       1.9
S1       P4      X     1.65      1.65
S1       P4      Y     -0.8      -0.88
S1       P4      Z     2.0       2.2

Expected dataframe after calculating distance between P1,P2 and P3,P4 for S1
Sample  Point   Axis  Value1    Value2

    S1       P1      X     1.2       1.28
    S1       P1      Y     3.4       3.6
    S1       P1      Z     1.4       1.6
    S1       P2      X     1.2       1.23
    S1       P2      Y     -3.4      -3.5
    S1       P2      Z     1.4       1.48
    S1       P3      X     1.65      1.68
    S1       P3      Y     0.8       0.96
    S1       P3      Z     2.0       1.9
    S1       P4      X     1.65      1.65
    S1       P4      Y     -0.8      -0.88
    S1       P4      Z     2.0       2.2
    S1       D1            6.8       7.1
    S1       D2            1.6       1.86

I want to calculate Euclidean distance between the points (P1, P2)
and (P3,P4) for both value1 and value2 and insert it back to the dataframe as new points D1 and D2
D1 is Euclidean distance between P1, P2
D2 is Euclidean distance between P3, P4
Here I have shown only one sample (S1) with 4 points (P1,P2,P3,P4), but in my data I have multiple samples (S1,S2,S3....etc) with the same four points(P1,P2,P3,P4)
I want to apply my calculation to each sample.
I am not sure how to achieve this


text:
Q: Get object with known pos. that I added to my grid I need to get one spicific object when I know excact possition of this object (for example on row 1 and column 2) that I previously added to my grid Hall.
I have class called Seats, this class stores info about rectangle and some methods. For better understading I paste code below
class Seats
{
    Rectangle rec = new Rectangle();
    Grid hall;
    int row;
    int column;
    //some other stuff

    public Seats(Grid hall, int row, int column)
    {
        this.hall = hall;
        this.row = row;
        this.column = column;
        rec = new Rectangle();
        //some othe stuff
    }

    //some methods and func.

}

public MainWindow()
{
    InitializeComponent();
    Grid hall = new Grid();

    int rows, columns, r, c;

    Config(out rows, out columns) //ask user for num of rows and columns

    //this just show my grid
    for (r = 0; r < rows; r++)
    {
        hall.RowDefinitions.Add(new RowDefinition());
        for (c = 0; c < columns; c++)
        {
            if (row == 0)
        {
            hall.ColumnDefinitions.Add(new ColumnDefinition());
        }
            Seats seat = new Seats(hall, r, c);
        }
    }
}

public void GetSeat(Grid hall, int onRow, int onColumn)
{
    //here I need to get object seat which is for example on position: row 1 column 2 and change some of propreties
}

I though about something like hall.GetValue(Grid.RowProperty, onRow), hall.GetValue(Grid.ColumnProperty, onColumn); could work.

A: instead of making the seats in a grid, what you should do is make them in a two stackpanels, one containing each row, the rows containing each object. so something like this
<!-- main stackpanel containing rows of seats -->
<StackPanel Orientation="Vertical" Name="WhereTheSeatsAre">
    <!-- one row -->
    <StackPanel Orientation="Horizontal">
        <!-- one of the seats -->
        <Rectangle (!the seat's properties here!)/>
    </StackPanel>
</Stackpanel>

and then when you get the seat in your "GetSeat()" function:
// I took out the "grid hall" because it's not needed, at least the way that this is written
//if you need the paramater replace "WhereTheSeatsAre" with the paramater name, but it has to be a stackpanel
public void GetSeat(int onRow, int onColumn) {
    // get the row as a stackpanel
    StackPanel rowUI = WheretheSeatsAre.Children[onRow] as StackPanel;

    // get the seat from the row
    Rectangle seat = rowUI.Children[onCollumn] as Rectangle;
}

also seeing the function name, consider this, which will make it return the seat, but it might make an instance:
public Rectangle GetSeat(int onRow, int onColumn) {
    // get the row as a stackpanel
    StackPanel rowUI = WheretheSeatsAre.Children[onRow] as StackPanel;

    // get the seat from the row
    Rectangle seat = rowUI.Children[onCollumn] as Rectangle;

    return seat;
}


text:
Q: C++ inheritance confusion #include<iostream>

using namespace std;

class Base{};

class Derived : public Base{};

int main() {
    Derived d;
    try {
        throw d;
    }

    catch(Base b) {
        cout << "1";
    }
    catch(Derived d) {
        cout << "2";
    }
    return 0;
}

Why is this program displaying output 1 and not 2? If I have thrown the Base class object and the output was 2, there won't be any problem as derived class is base class along with extra features. But is it the other way around?

A: Try .. Catch block always prefers the base class as priority.
if an early catch block handles a base class which has derived classes handled in catch blocks appeared below, then those derived class catch blocks will never hit - it designed in that way.
I can give a known example of std::exception class
suppose you have extended an exception class:
class AlgoException : public std::exception {}

try
{
    throw AlgoException ();
}
catch (std::exception) { std::cout << 1; }
catch (AlgoException ) { std::cout << 2; }

In above example the throw will never caught by second catch block - just NEVER
try
{
    throw AlgoException ();
}
catch (AlgoException ) { std::cout << 2; }
catch (std::exception) { std::cout << 1; }

If we do above then it will print '2' - this should be the approach of good programming practice while handling exception in try .. catch block. We should keep base class catch block below all the derived class catch blocks.
class AlgoException : public std::exception {}
class NewAlgoException : public AlgoException {}
try
{
    throw NewAlgoException ();
}
catch (AlgoException ) { std::cout << 2; }
catch (NewAlgoException ) { std::cout << 3; }
catch (std::exception) { std::cout << 1; }

If we do above then it will NEVER print '3' but prints '2'

the base class catch block must appear most below of it derived class
  catch block.


text:
Q: How to print or log from Python under Powershell I have a simple python script
name = input("Enter your name: ")
print ("Hello, " + name)

saved to test.py
I have a simple powershell script
python test.py

saved to Untitled2.ps1
Running Untitled2.ps1 from either the Powershell IDE or the command line cause no printing of the input request and no output. It hangs and has to be cancelled out. Entering data and pressing Return also cause no output.
Python 3.8.0, Windows 10, Powershell 5.1


text:
Q: How to redirect output from awk as a variable in python? Say I have a data file given below. The given awk command splits the files into multiple parts using the first value of the column and writes it to a file.
chr pos idx len
2   23  4   4
2   25  7   3
2   29  8   2
2   35  1   5
3   37  2   5
3   39  3   3
3   41  6   3
3   45  5   5
4   25  3   4
4   32  6   3
4   38  5   4

awk 'BEGIN {FS=OFS="\t"} {print > "file_"$1".txt"}' write_multiprocessData.txt

The above code will split the files as file_2.txt, file_3.txt ... . Since, awk loads the file into memory first. I rather want to write a python script that would call awk and split the file and directly load it into linux memory (and give unique variable names to the data as file_1, file_2).
Would this be possible? If not what other variations can I try.

A: I think your awk code has a little bug. If you want to incorporate your awk code into a python code that organizes all the things you wanna do try this:
import os
from numpy import *

os.system("awk '{if(NR>1) print >\"file_\"$1\".txt\"}' test.dat")

os.system works very well, however I did not know it is obsolescence. Anyway, as suggested subprocess works as well:
import subprocess

cmd = "awk '{if(NR>1) print >\"file_\"$1\".txt\"}' test.dat"
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)

A: There is no need for Awk here.
from collections import defaultdict
prefix = defaultdict(list)
with open('Data.txt', 'r') as data:
    for line in data:
        line = line.rstrip('\r\n')
        prefix[line.split()[0]].append(line)

Now you have in the dict prefix all the first fields from all the lines as keys, and the list of lines with that prefix as the value for each key.
If you also wish to write the results into files at this point, that's an easy exercise.
Generally, simple Awk scripts are nearly always easy and natural to reimplement in Python. Because Awk is very specialized for a constrained set of tasks, the Python code will often be less succinct, but with the Python adage "explicit is better than implicit" in mind, this may actually be a feature from a legibility and maintanability point of view.


text:
Q: how can i stretch a video in VideoView - Android Every time I show a movie on the screen I see white stripes on the sides. How can I stretch the movie to fit the screen???
Everywhere I see the following code:
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"

But it is not stretching the movie, it only stretches the VideoView and I Still see the white stripes on the sides.