text:
Q: Liferay Portlet: How to generate service.xml (service builder) from existing database I am new to liferay, Can anyone please suggest some way to generate the service.xml for existing database Discussion on Liferay Website . I hope people might have developed some way or liferay have developed some plugin for this.

A: I see no particular use in introducing servicebuilder to large existing databases: You can connect servicebuilder entities to "legacy datasources" or "legacy tables" (those make good search terms) but service.xml generation has not been done AFAIK.
Some problem with this approach are:

*

*servicebuilder has certain assumptions about operations in a database. It's done to encapsulate all different databases that Liferay runs on, thus might not use every database to its fullest extent possible

*If you have a large existing database, you probably have a lot of existing business logic to make sure correct data goes in and out of the database. You might even work with stored procedures etc.

*While you can make servicebuilder work with stored procedures, you'd have to introduce custom sql to work around servicebuilder's assumptions. Same goes for explicit foreign key relationships etc.

My recommendation is to rather have a proper interface on the existing business logic, e.g. Webservice, JSON, Rest, whatever is popular. Then use this interface in Liferay's portlets.
Another option might be to bring the existing persistence code into Liferay and just expose services without making use of the persistence features of Servicebuilder. For this you'd just define empty <entity> blocks (with names etc). This will generate the appropriate DoSomethingLocalService, but omit the persistence implementation - and you can wire your existing code in these services.

A: You can go through below link to understand Service Builder in liferay
https://www.liferay.com/documentation/liferay-portal/6.0/development/-/ai/service-build-2
Also below link have sample service builder portlet
https://www.liferay.com/community/forums/-/message_boards/message/17609606
Hope it Helps !

A: Not done yet AFAIK. Since Liferay directly doesnot support all data properties of DB like foreign key, one to n mapping etc, it is a challenge to create the reverese engineering. But you can give a try.

A: Service Builder is generally a nice feature to create relatively small databases, and simple business Logic, while giving you the advantage that your tables will be auto-generated when you deploy your portlet, and having finders (search by X attribute) with no effort. If this is the case with your database, it will be much easier to create a new service.xml from scratch.
Other that that, I think that having an extended database in Liferay's Service Builder will introduce more problems and slow development while you're implementing a complex business Logic, create custom Finders whenever you need to query on a join of tables and so on. So it seems quite normal to me that a conversion of a database to Service Builder is not available.
In other words, if your database is too large to write it in service.xml, you shouldn't use Service Builder in the first place


text:
Q: bitwise operations robot framework I have a keyword which returns a integer and I need to write another keyword that will extract the info from it.
each bit in the byte indicates a motor is running, and multiple motors could be active at the same time
    motor:
    - 0: Station 1 active
    - 1: Station 2 active
    - 2: Station 3 active
    - 3: Station 4 active
    - 4: Station 5 active
    - 5: Station 6 active
    - 6: Station 7 active
    - 7: Station 8 active

Unable to find any documentation on bitwise operations in Robot Framework.
Thank you

A: Robot Framework is too high level and also has very close relations with Python which has all these operators, so it does not implement any kind of operator of its own, not even the basic arithmetic ones. All you have are keywords and Python.
There are two approaches you could choose from.

*

*Implement the logic you need in pure Python as a library for Robot Framework.

*Create a user keyword in Robot Framework utilizing the existing Evaluate keyword to do the logic.

Either way you will have to do the bit manipulation in Python and then wire that into Robot Framework. Both topic should have plenty of documentation available beside the ones I have linked.

redpajama_set_name: RedPajamaStackExchange


text:
Q: git monorepo with multiple projects I want to have an umbrella repo (monorepo) with multiple projects in such a way that I should be able to clone each project individually, modify and push without having to clone the whole monorepo.
monorepo
  |
  --- project1_repo
  |
  --- project2_repo
  |
  --- project3_repo

E.g. I should be able to clone project2_repo, modify it and then git push without having to clone the whole monorepo with all projects.
What would be the best approach?
Is git submodule the only way for this?

A:
I should be able to clone project2_repo, modify it and then git push without having to clone the whole monorepo with all projects.

If you are not using submodules or subtrees, you can still work with only one repository by doing a git sparse-checkout as explained in "Get up to speed with partial clone and shallow clone"
That way, you can work on the part of the monorepo you need, without cloning everything.

A: I have been working on solving this exact problem for a few years now: https://github.com/josh-project/josh
It does require some setup (running a service in your infra), but then enables treating any part of your monorepo as an individual project repo.
git sparse-checkout can also work potentially, but does not cover the use case where you want to collaborate on some of your individual projects out of the monorepo context. That is, for example, you have a monorepo containing both private and and open source projects and you want to bidirectionally mirror the open source parts to a public site, like github.com.


text:
Q: Why is pgrouting astar not consistent? I route from 1 end of a circular route to the opposite end. Visually it is obvious that going clockwise is shorter, however shortest_path_astar sometimes picks clockwise and sometimes anti-clockwise.

I narrowed down the amount of edges it may route on and it seems that the order in which the selected edges appear in the result set make a difference in the outcome of astar (which should not happen in my opinion).
Set1:
SELECT e.id, e.source_id::integer as source,    e.target_id::integer as target, (SELECT SUM(n.shape_leng::float) FROM netwerk n    WHERE e.source_id = n.source_id    AND e.target_id = n.target_id) as cost,    ST_X(source.the_geom) as x1, ST_Y(source.the_geom) as y1, ST_X(target.the_geom) as x2, ST_Y(target.the_geom) as y2 FROM edges e JOIN knooppunten source    ON source.gid = e.source_id JOIN knooppunten target ON target.gid = e.target_id where e.id in (127,757,471,286,579,601,760) or not exists (SELECT * FROM netwerk n    WHERE e.source_id = n.source_id    AND e.target_id = n.target_id);

Result1:
 id  | source | target |       cost       |        x1        |        y1        |        x2        |        y2
 -----+--------+--------+------------------+------------------+------------------+------------------+------------------
 127 |    459 |    460 | 1166.62881971498 | 178418.026099999 |      593089.0845 | 179488.144699998 | 592656.112100001
 286 |    457 |    373 | 2701.89635124091 | 177301.707899999 |      593119.0339 | 177093.187399998 | 590500.850200001
 471 |    457 |    458 | 229.123075139216 | 177301.707899999 |      593119.0339 | 177516.643399999 | 593197.757599998
 579 |    371 |    373 | 1291.71083699618 | 178363.840300001 |      590548.6774 | 177093.187399998 | 590500.850200001
 601 |    460 |    371 | 2456.81983676712 | 179488.144699998 | 592656.112100001 | 178363.840300001 |      590548.6774
 757 |    459 |    458 | 919.539772037522 | 178418.026099999 |      593089.0845 | 177516.643399999 | 593197.757599998
 760 |    372 |    373 | 805.921542501888 |      176324.6664 | 590358.514199998 | 177093.187399998 | 590500.850200001
 (7 rows)

Set2:
SELECT e.id, e.source_id::integer as source,    e.target_id::integer as target, (SELECT SUM(n.shape_leng::float) FROM netwerk n    WHERE e.source_id = n.source_id    AND e.target_id = n.target_id) as cost,    ST_X(source.the_geom) as x1, ST_Y(source.the_geom) as y1, ST_X(target.the_geom) as x2, ST_Y(target.the_geom) as y2 FROM edges e JOIN knooppunten source    ON source.gid = e.source_id JOIN knooppunten target ON target.gid = e.target_id where e.id in (127,757,471,286,579,601,760);

Result2:
 id  | source | target |       cost       |        x1        |        y1        |        x2        |        y2
 -----+--------+--------+------------------+------------------+------------------+------------------+------------------
 579 |    371 |    373 | 1291.71083699618 | 178363.840300001 |      590548.6774 | 177093.187399998 | 590500.850200001
 760 |    372 |    373 | 805.921542501888 |      176324.6664 | 590358.514199998 | 177093.187399998 | 590500.850200001
 471 |    457 |    458 | 229.123075139216 | 177301.707899999 |      593119.0339 | 177516.643399999 | 593197.757599998
 286 |    457 |    373 | 2701.89635124091 | 177301.707899999 |      593119.0339 | 177093.187399998 | 590500.850200001
 127 |    459 |    460 | 1166.62881971498 | 178418.026099999 |      593089.0845 | 179488.144699998 | 592656.112100001
 757 |    459 |    458 | 919.539772037522 | 178418.026099999 |      593089.0845 | 177516.643399999 | 593197.757599998
 601 |    460 |    371 | 2456.81983676712 | 179488.144699998 | 592656.112100001 | 178363.840300001 |      590548.6774
 (7 rows)

Above 2 result sets are identical apart from the ordering of the rows. When i use shortest_path_astar on these 2 result sets i get different results:
select * from shortest_path_astar('<select Set1>', 460, 373, false, false) astar;
 vertex_id | edge_id |       cost
-----------+---------+------------------
       460 |     127 | 1166.62881971498
       459 |     757 | 919.539772037522
       458 |     471 | 229.123075139216
       457 |     286 | 2701.89635124091
       373 |      -1 |                0

select * from shortest_path_astar('<select Set2>', 460, 373, false, false)      vertex_id | edge_id |       cost
-----------+---------+------------------
       460 |     601 | 2456.81983676712
       371 |     579 | 1291.71083699618
       373 |      -1 |                0

In this example Astar gives different results for an identical set of rows.
Other things i noticed:

*

*If i route from endpoint to startpoint (373 -> 460) shortest_path_astar gives the correct answer.

*If i use shortest_path instead of shortest_path_astar this particular problem does not occur.

*If i change the type of x1,x2,y1 and y2 to double precision or float8 (what it should be according to docs) shortest_path_astar still is incorrect

*If i change the type of x1,x2,y1 and y2 to int or bigint shortest_path_astar gives the correct answer

My best guess is that the heuristic function in the underlying Boost library is messing up because of how it interprets the incoming x1,x2,y1 and y2. Chances that the boost library is wrong seem slim so it might be the transfer of the data i feed it.
Does any of you have experience with this behaviour of shortes_path_astar or knows what/if i am doing wrong?

*
-

A: Your guess with the heuristics function was correct, I think. A-star's heuristics settings are (badly) defined assuming a projection in degree. With a meter projection as in your case they might have to be configured with different values.


text:
Q: What's the purpose of the PriorityBlockingQueue? I've been playing with blocking queues and PriorityQueue, and it got me thinking. I can't see a good usecase for PriorityBlockingQueue. The point of a priority queue is to sort the values put into it before they're retrieved. A blocking queue implies that values are inserted into it and retrieved from it concurrently. But, if that's the case, you'd never be able to guarantee the sort order.
BlockingQueue<Integer> q = new PriorityBlockingQueue<>();

new Thread (()->{ randomSleep(); q.put(2); randomSleep(); q.put(0); }).start();
new Thread (()->{ randomSleep(); q.put(3); randomSleep(); q.put(1); }).start();

ArrayList<Integer> ordered = new ArrayList<>(4);
for (int i = 0; i < 4; i++) {
    randomSleep();
    ordered.add(q.take());
}
System.out.println(ordered);

In this example, the order in which the main thread gets the offered values is quite random, which seems to defeat the purpose of a priority queue. Even with a single producer and single consumer, the order can not be ensured.
So, what is the use of PriorityBlockingQueue then?

A:
In this example, the order in which the main thread gets the offered
values is quite random

Well you have a race-condition during the insertion and the retrieve of those elements. Hence, the reason why it looks random.
Nonetheless, you could use for instance the PriorityBlockingQueue to sequentially field up with some elements (or tasks) that need to be pick up by multiple threads in parallel by their highest priority element/task. In such case you can take advantage of the thread-safe properties of a structure that guarantees you that the the highest priority element is always ordered first.
One example would be a Queue of tasks in which those tasks have a priority, and you want those same tasks to be processed in parallel.


text:
Q: How do I use Wikipedia's search option "deepcat"? I'm developing a small application where an user can select a conceptual category (Physics, Biology, History, etc.) existing on Wikipedia to fetch random articles from, and I'm using the MediaWiki API in order to perform this. Unfortunately the majority of Wikipedia's articles are categorized under deeper subcategories, so once a generic category gets selected, it would be great for me to be able to fetch articles from its subcategories as well.
Enter deepcat. According to its documentation, deepcat is an option (gadget) users can enter in Wikipedia's search bar to fetch articles from a category and its subcategories, for example:
deepcat:Mathematics
should return articles from the category "Mathematics" and its subcategories. The problem is, it doesn't seem to work. The only message I receive back is:

A warning has occurred while searching: Deep category query returned
  too many categories

Wikipedia's search option and MediaWiki APIs both seem to return the same result, so it's not a matter of how my calls are written. Moreover, the search appears to be case sensitive: if I instead write deepcat:mathematics I get back the 9 articles currently classified under Categoty:Mathematics, but no articles from its subcategories.
How do I fix this?

A: Public categories like (Physics, women, politicians...etc) have too much pages when your try to fetch it. That's why you see this error.
There is a tool called PetScan hosted by Wikimedia labs. You can easily type the category title, then select the depth you want to reach, and then it's done!. https://petscan.wmflabs.org/
Also, see how it works https://meta.m.wikimedia.org/wiki/PetScan/en


text:
Q: Error if scipy is frozen into an executable with cx-Freeze at the moment I am facing a problem regarding scipy and cx-Freeze.
Windows 7 Enterprise (64-Bit);
Python 3.5.2|Anaconda 4.2.0 (64-bit);
scipy 0.18.1;
cx-Freeze 5.0.1;

I want to freeze a python script into an executable. Below you find the source code and the freeze script.
main.py
import scipy

if __name__ == '__main__':
    print('Test dirstribution methods!')

That's the main.py file.
setup.py
import sys
from cx_Freeze import *

packages = ['numpy']
excludes = ['tkinter']

distTest_Target = Executable(
    script = "main.py",
    base = "Console",
    shortcutName="distTest",
    targetName = "distTest.exe"
)

build_exe_options  = {
    "packages": packages,
    "excludes":excludes
}

setup(name='distTest',
    version='1.0.0',
    description='distTest (64-bit)',
    options = {"build_exe": build_exe_options},
    executables=[distTest_Target]
)

The build process executes without errors, but if I try to start the exe I get the following Error:
Figure: Error during execution of exe
If I try to add 'scipy' to the package list like packages = ['numpy','scipy'] I get another error during the build process: Figure: scipy ImportError.
Has anybody an idea what is wrong there? Thank you in advance for your help!

A: Installing the latest version of Anaconda (4.3.1) and editing hooks.py in the cx_freeze package:
finder.IncludePackage("scipy.lib")

replaced by:
finder.IncludePackage("scipy._lib")

solved the problem.


text:
Q: Как сделать кнопку с выпадающим списком команд в aiogram? Как сделать кнопку, после нажатия которые показывается весь список команд с описанием?
Пример

A: Для этого нужно написать в Botfather в Телеграм.
Вводите команду /mybots , открывается список ваших ботов. Выбираете нужный. У вас открывается меню. Здесь нужно выбрать Edit Bot, а затем Edit Commands.
Ну или можно организовать следующим образом. Создать словарь с командами и описанием.
commands = {'/start': 'Нажмите для запуска бота', '/help': 'Нажмите для просмотра доступных команд'}

И уже из него вытягивать инфу в сообщение. Либо выводить на нового члена чата, либо на определённую команду.
@dp.message_handler(content_types=['new_chat_member'])
# или
@dp.message_handler(commands=['help'])
async def commands(message: types.Message)
    for command, discription in commands:
        await bot.send_message(message.from_user.id, f'{command}\n{discription}')

Можно и клавиатуру сразу прикрутить в сообщение. Собрать из ключей словаря.


text:
Q: Is it possible to use powershell to authenticate AD user so they can log on later offline I would like to create a user account in active directory that will be able to log in to any machine in the directory. I have a situation where the first time the user actually touches a machine it will not be on the network, and I don't know ahead of time which machines they will be using.
Normally after creating the user, you have to log in with the account while the machine is on the network with the directory server before that account can log in offline.
I know GPO can push powershell scripts and run them.
I would like to push and run a powershell script to all the machines while I have them on the network that would authenticate this user's account so that I don't have to manually log in to it before giving the user a machine.
Is this possible and what help pages would I need to look at?


text:
Q: Escape nested template in ansible/jinja2 In ansible/jinja2 one needs to escape double braces: {{.Foo}} should be {{'{{'}}.Foo{{'}}'}}.
But how do I escape a nested template? e.g.
- name: Find running containers on swarm/non-swarm hosts
  shell: "{{item}}"                                        # <------ problem here
  loop:
    - { "docker stack ls --format '{{'{{'}}.Name{{'}}'}}'" }
    - { "docker ps -a    --format '{{'{{'}}.Names{{'}}'}}'" }
  register: result

The problem is the loop item undergoes templating again, in the shell: line.
Error:

...template error while templating string: unexpected '.'

A: You will want the {% raw %} and {% endraw %} blocks in jinja, although be aware that your use of {{ item }} like that makes you subject to ansible's recursive jinja evaluation, which is what I suspect is tripping you up even right now with your {{ {{ }} business
- debug:
    msg: |
      {% raw %}
      docker stack ls --format '{{.Name}}'
      docker ps -a    --format '{{.Names}}'
      {% endraw %}

Although you might also be happier using the actual ansible module designed for working with docker

A: Due to templating of item which contains the {{ Jinja delimiters escaping them is complex. As @mdaniel suggested, it might be simpler to use an ansible module designed to working with docker. One slightly hacky way to make Jinja delimiters to be ignored is to use the concat operation with the item inside a Jinja context.
Something like this:
  tasks:
    - shell: "{{ 'docker ' ~ item.cmd ~ ' --format ' ~ '\"' ~ '{{ ' ~ item.pattern ~ ' ' ~ '}}' ~ '\"' }}"
      register: docker_cmd
      loop:
        - cmd: 'ps -a'
          pattern: '.Names'
        - cmd: 'stack ls'
          pattern: '.Name'

It does look very cryptic, but seems to work.


text:
Q: How to include .ps files in latex and put three of them with text in one page? I have .ps files, I want to prepare one pdf page, Then I want to show my files (.ps images) in the page in a way that divide the page to four section the top left section contains the text (e.g name, snr, time ... of my files) and the other three sections content my graph which is my ps file themselves.
How would I be able to do that?
Here is the code:
\documentclass{article}
\usepackage{graphicx}
\usepackage{subcaption}

\begin{document}

\newpage
\begin{figure}
\begin{minipage}[c][0.4\textheight][c]{\linewidth}
  \begin{enumerate}
  \item name  hjjk
  \item snr  1522
  \item obser time  25885
  \end{enumerate}
\end{minipage}

\begin{subfigure}[!htbp]{0.6\textwidth}
\centering
\includegraphics[width=\linewidth]{10_freq_phase.png}
\end{subfigure}

\begin{subfigure}[t]{0.6\textwidth}
\centering
\includegraphics[width=\linewidth]{10_pulse_profile}
\end{subfigure}

\begin{subfigure}[]{0.6\textwidth}
\centering
\vspace{0pt}% set the real top as the top
\includegraphics[width=\linewidth]{10_sub_int}
\end{subfigure}
\end{figure}

\end{document}

A: Is this what you want?
\documentclass{article} %
\usepackage[showframe]{geometry}
\usepackage[demo]{graphicx} %
\usepackage{subcaption}
\usepackage{enumitem}
\begin{document}

\newpage
\begin{figure} [!htbp]
\begin{minipage}[c][0.4\textheight][c]{0.45\linewidth}
 \begin{enumerate}[wide = 0pt]
 \item name hjjk
 \item snr 1522
 \item obser time 25885
 \end{enumerate}
\end{minipage}
%%
\begin{subfigure}{0.45\textwidth}
\centering \includegraphics[width=\linewidth]{10_freq_phase.png}
\caption{}
\end{subfigure}
\vspace*{-6ex }

\begin{subfigure}[c]{0.45\textwidth}
 \centering \includegraphics[width=\linewidth]{10_pulse_profile}
\caption{}
 \end{subfigure}
 \qquad
\begin{subfigure}[c]{0.45\textwidth}
\centering \vspace{0pt}% set the real top as the top
\includegraphics[width=\linewidth]{10_sub_int}
\caption{}
\end{subfigure}
\end{figure}

\end{document}


text:
Q: Retornar resultado em um campo esta é minha primeira pergunta aqui...
Como retornar este valor que está no console.log(converte) para o input com #fahrenheit, que já guardei em uma variavel com mesmo nome?  Já tentei:
document.querySelector('#fahrenheit').innerText = converte

Mas não funcionou. textContent também não.
document.querySelector('#temp-form').addEventListener('submit', calcular);

//função calculadora

function calcular(e){
// pegar o valor em Celsius
const celsius = document.querySelector('#celsius');

// calculos
const principal = parseFloat(celsius.value);
const converte = parseFloat((9 * principal + 160) / 5);

console.log(converte);

 e.preventDefault();
}

Além disso, o parseFloat parece não funcionar, pois o campo rejeita valores decimais. Porque?
Segue o HTML:
<!doctype html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css">
<title>Conversor de Temperatura</title>

Conversor de Temperatura

                  <form id="temp-form">

                              ºC
                              <input type="number" class="form-control" id="celsius" placeholder="Temperatura em Celsius">

                            <input type="submit" value="Calcular" class="btn btn-danger btn-block">

                  </form>

Resultados

                            Fahrenheit
                            <input type="number" class="form-control" id="fahrenheit" disabled>

A: Com é sua primeira vez, precisa colocar todas as informações, por exemplo, o <form>, mas, acabei criando um exemplo minimo:

document.querySelector('#temp-form')
        .addEventListener('submit', calcular);

function calcular(e)
{
  var celsius = document.getElementById('celsius');
  var principal = parseFloat(celsius.value);
  var converte = parseFloat((9 * principal + 160) / 5);
  document.getElementById('fahrenheit').innerText = converte
  e.preventDefault();
}
<form id="temp-form" name="temp-form">
 <input type="text" id="celsius" name="celsius" />
 <button>Calcular</button>
</form>

A: Complementando a resposta do Virgílio Novic e abordando a questão do input não aceitar decimais.
Na resposta acima citada, basta trocar o .innerText por .value:
document.getElementById('fahrenheit').value = converte;

Em relação à decimais, coloque o atributo step no input. O type="number" por padrão só aceita números inteiros. O step permite redefinir esse padrão da forma que achar melhor:
<input type="number" step=".01"...

No exemplo acima, o valor .01 irá permitir 2 casas decimais pulando de 1 em 1 centésimo.
Outros exemplos básicos:
step=".00"   -> 2 casas decimais pulando de 1 em 1 inteiro
step=".001"  -> 3 casas decimais pulando de 1 em 1 milésimo
step=".1"    -> 1 casa decimal pulando de 1 em 1 décimo
step=".10"   -> 2 casas decimais pulando de 1 em 1 décimo
step="any"   -> aceita qualquer valor float (sem número definido de casas decimais)


text:
Q: How can I let Javascript know when I select an option value? So I have a list of option values that, when they are selected, I want to pass information to Javascript, so that I can try to have Javascript contact the server and update several other fields based on that option value (AJAX - something I'm new to!)
How do I let Javascript know that I selected a particular option value?

A: You can bind a change event listener to the select element (this assumes your select element has an id of yourSelect):
document.getElementById("yourSelect").onchange = function() {
    var selected = this.value;
    //Do whatever with the selected value
}

Here's a working example. The onchange event listener is called whenever the value of the select changes. You can access the value of the selected option with this.value, and pass that to your server side script.

A: In ugly direct-coding methods:
<select onchange="the_select_was_changed(this);">
     <option>...</option>
     <option>...</option>
</select>

function the_select_was_changed(obj) {
    alert("The selected index is " + obj.selectedIndex + " and has value " + obj.options[obj.selectedIndex]);
}

A: add for each selectboxes the event onChange:
<select name="{any name}" onChange="myVJsValuecheckFunction(this)">
  <option value="{myOptionValueOne}">myoptionText</option>
  ...
</select>

Then write the javascript function:
function


text:
Q: Trunc date in shell? I need to transform the current date in seconds but the current date must be first  truncated to midnight.
From 2018-05-25 13:30:30 to 2018-05-25 00:00:00.

Is there an equivalent for trunc(sysdate) from oracle?

A: You can use date on the shell to achieve this.
date -d "2018-05-25 13:30:30" "+%F 00:00:00"

which will output
2018-05-25 00:00:00

Here is a version which uses date twice to first get todays date truncated and then turns it into epoch seconds.
date -d "`date '+%F 00:00:00'`" "+%s"


text:
Q: User Permission in Jenkins Inside Jenkins Jobs & Builds folder, I am creating a text file and writing some content through Java program. As I am part of corporate network, I am inside firewall with many security rules where I have been restricted to write/update the program files directory under C: drive. Although I am administrator in my local machine, however the company policies are still applied which is denying me access to write/delete any files from the Jenkins directory. I see Jenkins is nicely reading/modifying/writing any files/folders without any issues which is believed to the typical behavior of Jenkins's USER.
Question 1: Is there any way I can use this Jenkins's user through my code so I can avail access on to these directories?
Question 2: Are there ways to solve this issue through Java code? (Note: I have tried writing a file with Run as Administration java code as well)
Kindly let me know if I am missing any details,.any help is highly appreciated.

A: If you want your application to run with same credentials as Jenkins user, then hold Shift+Right Click your application, select "Run as different user", provide Jenkins's user credentials and press OK.
If you are launching your Java application from command line, do the Shift+Right Click on the cmd.exe first, and once again select "Run as different user"
If you want to impersonate a Windows user from within code, then you should really reword your question body and title (and remove Jenkins references as it has nothing to do with this). But even in this case, you need to know the credentials of the user you are trying to impersonate

A: It's about the user who launched the jenkins server, who might have the permissions to access the directories.
You can use the same user for your operations if available.
Question 1: Is there any way I can use this Jenkins's user through my code so I can avail access on to these directories?
Jenkins users - Jenkins server can have its own users and privileges can be set for each users differently. You cannot use these users outside of Jenkins server.
You can use the user who launched the Jenkins server, must be a user at OS level.
Question 2: Are there ways to solve this issue through Java code? (Note: I have tried writing a file with Run as Administration java code as well)
Again, only OS level users can be used and not the Jenkins users(users created inside Jenkins server)


text:
Q: vertical align grid container I managed to get the grid for my simple layout. Now I would like to center it vertically. How can I get it done? Important: I mean the whole wrapper (wrapping container/ whole grid), not the items within the container...
And a second question concerning this issue: is this effecting "grid-auto-flow: row dense;"?

html {box-sizing: border-box;}

body {}

.wrapper {
  display: grid;
  width: 100%;
  grid-column-gap: 5px;
  grid-row-gap: 5px;
  grid-template-columns: 20% 20% 20%;
  grid-template-rows: 25% 25% 25%;
  justify-content: center;
  align-content: center;
  grid-auto-flow: row dense;
  }

.box
   {padding: 15px;
    border: 1px solid red;
    background: grey;}

.a {grid-column: 1 / span 2;
    grid-row: 1 / span 2;}

.b {grid-column: 3; grid-row: 1}

.c {grid-column: 3; grid-row: 2;}

.d {grid-column: 1; grid-row: 3}

.e {grid-column: 2; grid-row: 3}

.f {grid-column: 3; grid-row: 3}

A: I assume you already know how to vertically center items inside a css grid.
What you could do now is to create yet another wrapper-of-wrapper div whose layout is either flexbox (vertical) or grid (with just 1 row and 1 column), then put your wrapper inside it.

html {box-sizing: border-box;}

.wrapper-of-wrapper {
    position: fixed;
    width: 100%;
    height: 100%;

    display: flex;
    flex-flow: column nowrap;
    justify-content: center;
}

.wrapper {

    height: 80%;

    display: grid;
    grid-column-gap: 5px;
    grid-row-gap: 5px;
    grid-template-columns: 20% 20% 20%;
    grid-template-rows: 25% 25% 25%;
    justify-content: center;
    align-content: center;
    grid-auto-flow: row dense;
}

.box {
    padding: 15px;
    border: 1px solid red;
    background: grey;
}

.a {grid-column: 1 / span 2;
    grid-row: 1 / span 2;}

.b {grid-column: 3; grid-row: 1}

.c {grid-column: 3; grid-row: 2;}

.d {grid-column: 1; grid-row: 3}

.e {grid-column: 2; grid-row: 3}

.f {grid-column: 3; grid-row: 3}

If you just want the wrapper to center in the flexbox but not to resize with it, set its height to auto and flex to 0 0 auto so that it will size to content, and will not shrink or grow.


text:
Q: Interpreting coefficients of ordinal independent variables in logistic regression in R I have conducted a logistic regression in R
> Model <- glm(A ~ B + C, family = "binomial", data = Data)
> summary(Model)

Coefficients:
                    Estimate Std. Error z value Pr(>|z|)
(Intercept)          -1.6138   678.6939  -0.002   0.9981
BPu                   1.0003     0.5539   1.806   0.0709 .
C.L                  21.2450  2146.2181   0.010   0.9921
C.Q                   1.2210  1813.8853   0.001   0.9995
C.C                   9.8965  1073.1091   0.009   0.9926
C^4                  -0.3275   405.5973  -0.001   0.9994

exp(coef(Model))

       (Intercept)           BPu               C.L                 C.Q
      1.991295e-01       2.719031e+00       1.684921e+09       3.390646e+00
          C.C             C^4
       1.986151e+04       7.207529e-01

As I understand it when the independent variable, B, (a binary variable) changes to Pu this is associated with an increase in the log odds of a "success" in the dependent by 1.0003, or that odds of increasing the dependent variable are multiplied by 3.22 relative to the intercept, and this change is near significant.
Can I say a similar statement for the variable CR, a 5 level ordinal variable? I've found online that L, Q, C, ^4 represent linear quadratic, cubic ... but I haven't found an answer outlining what I can practically say about these coefficients or how to interpret them.
I understand that the influence is likely to be insignificant, but which P value do I use? What can I say about the other coefficients?

A: I think a lot of your answers can be found in the answer to a similar question. The one caveat is that the linear, quadratic, cubic, and quartic terms do not directly correspond to numeric effects as though you used the factor levels as a raw number. You can see this by typing contr.poly(5) in $R$ to see how the various levels are coded (beyond the intercept = constant = all 1's).

A:
I understand that the influence is likely to be insignificant, but which P value do I use? What can I say about the other coefficients?

The model turns the single categorical/ordinal variable effectively into 4 variables and reports coefficients and error estimates for each independently.
If you want a single p-value then what you can do is compare two models with and without the addition of the $C$ parameter and use that p-value for the significance. This comparison can be made with a chi-square test.
Below is an example
### generate data with approximately equal z-values for the ordered class polynomial categories
set.seed(1)
n = 100
class = c(rep(c(1,2,3,4,5),n))
class_val = poly(c(1,2,3,4,5),4)[,] %*% 1/c(1.996,3.688,5.525,3.747)
class_val
#             [,1]
# [1,] -0.59036857
# [2,]  0.08605809
# [3,]  0.71579404
# [4,] -5.64019429
# [5,]  5.42871073
y = rbinom(length(class), 1, p = (1+ exp(-1-1*class_val[class,1]) )^-1 )

### use two models on e with and one without the class
mod0 = glm(y ~1, family = binomial)
mod1 = glm(y ~ ordered(class), family = binomial)

### summary of results
summary(mod1)
anova(mod0,mod1,test="Chisq")

The table with t-tests is not significant
> summary(mod1)

Call:
glm(formula = y ~ ordered(class), family = binomial)

Deviance Residuals:
     Min        1Q    Median        3Q       Max
-1.94788  -0.20101   0.00013   0.57012   2.79715

Coefficients:
                 Estimate Std. Error z value Pr(>|z|)
(Intercept)         3.744    130.453   0.029    0.977
ordered(class).L    9.599    412.528   0.023    0.981
ordered(class).Q    9.881    348.650   0.028    0.977
ordered(class).C    9.248    206.265   0.045    0.964
ordered(class)^4    4.563     77.962   0.059    0.953

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 632.75  on 499  degrees of freedom
Residual deviance: 319.38  on 495  degrees of freedom
AIC: 329.38

Number of Fisher Scoring iterations: 17

But a chi-squared test is significant
> anova(mod0,mod1,test="Chisq")
Analysis of Deviance Table

Model 1: y ~ 1
Model 2: y ~ ordered(class)
  Resid. Df Resid. Dev Df Deviance  Pr(>Chi)
1       499     632.75
2       495     319.38  4   313.38 < 2.2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The reason for the difference is because I constructed this example on purpose to have all the linear, quadratic, cubic and quadratic coefficients to be more or less equal and with an equal moderate effect. But the anova function compares all of them together.
(with this example I am not saying whether your case is gonna do the same, but it is to stress that this type of test is different from individual t-tests)


text:
Q: ADFS authentication is not passed to a webmethod in an application page in the _layouts I recently configured a sharepoint 2013 farm to use ADFS and converted the web application successfully, every thing is working fine except one thing, in my portal i have multiple webparts that communicate to webmethods (GET,POST) using Ajax jquery calls, these webmethods are hosted in an application page which resides in the _layouts.
my farm has 2 web front end, now the problem that sometimes these webmethods cannot see the logged in user so spcontext.current.web.currentuser is null.
and i noticed that sometimes i notice multiple logins even though i am already logged in and i have changed the servicetokenexpirationwindow to 4 days!
the session state is configured in the farm and enabled in the web application.
our azure load balancer is configured to keep the client ip to stick with the same machine.
Please help me!


text:
Q: Altair renderer silently failing I followed the detailed install instructions for Altair on a jupyter notebook.   I'm trying to install this on my virtualenv hosted on pythonanywhere.
However, when I ran the demo script, the chart never appears.  This is despite me specifying alt.renderers.enable('notebook')
This is what the notebook looked like:

Not sure what else to try on this -- I believe all the libraries are up to date.  My only other thought is that the actual notebook server is running on older python.  Not sure if I'm able to update the notebook server here on pythonanywhere (or if that would even help)

The only other wildcard -- is chrome OSX a problem?  So I tried this from Safari and got the identical result.
=============
Followup:
Looking at the javascript console in the Chrome Developer Tools doesn't show any errors. (I think I'm using the console correctly)
I ran this twice (with kernel restarts) to show that the alt.chart() does seem to generate something,  because when I run w/o the rendering code, it warns me about this.

A: I suspect your vega jupyter notebook extension is not installed correctly. It should be automatically installed if you have notebook version 5.3 or newer, but it looks like you may have an older version of the notebook package.
To fix this, try running the following:
pip install -U jupyter notebook
pip install -U vega
jupyter nbextension install --sys-prefix --py vega

More information can be found at https://github.com/vega/ipyvega

A: Unfortunately the PythonAnywhere jupyter notebooks are running on v4.2, and Altair requires v5.3+. It is not something you can change/upgrade on your end, and you will have to wait for a PythonAnywhere system upgrade for the Altair code to run. Sorry!


text:
Q: Displaying Panoramio thumbnail layer on Google Maps using REST I'm trying to display a layer of thumbnail images on my Google Map via Panoramio. The Panoramio is RESTful and its homepage states a simple GET request must be submitted on the API url.
I don't have much experience with REST and have tried just to get the API to respond with text before I can process the JSON that is supposed to result from the call. I don't have much experience with AJAX, could smeone point me in the right direction? Here is my pertinent code thus far:
**HTML**

**JS**
var xmlhttp = new XMLHttpRequest();
var thumbUrl = "http://www.panoramio.com/map/get_panoramas.php?set=public&from=0&to=20&minx=-180&miny=-90&maxx=180&maxy=90&size=medium&mapfilter=true"
xmlhttp.open("GET", thumbUrl, true)
xmlhttp.send();
document.getElementById('backdiv-pix').innerHTML=xmlhttp.responseText;

My browser is throwing the following error:
Cannot set property 'innerHTML' of null
Some guidance would be much appreciated.
MS

A: There is no div with id="backdiv-pix" in your code.  Either change:

To:

Or use document.getElmentByClassName('backdiv-pix')[0].innerHTML=xmlhttp.responseText
However, once you fix that typo, you will need to deal with this:
XMLHttpRequest cannot load http://www.panoramio.com/map/get_panoramas.php?set=public&from=0&to=20&minx=-180&miny=-90&maxx=180&maxy=90&size=medium&mapfilter=true. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.

working fiddle
code snippet:

var xmlhttp = new XMLHttpRequest();
var thumbUrl = "http://www.panoramio.com/map/get_panoramas.php?set=public&from=0&to=20&minx=-180&miny=-90&maxx=180&maxy=90&size=medium&mapfilter=true&callback=?"
$.getJSON(thumbUrl, function(data) {
  document.getElementById('backdiv-pix').innerHTML = JSON.stringify(data);
});


text:
Q: Trouble with joinning tables Here is my database tables, i want to echo everything with join, but its dosnt work.
Products table:
id category_id img name price price_action in_stock category description youtube

Category table:
 category_id category_name

Here is my code, how to want list everything, but its dosnt work:
<?php
    include ("../db_config.php");

    $sql[0] = "SELECT * FROM products RIGHT JOIN category ON category.category_name=products.category_id";

    $result= mysqli_query($conn,$sql[0]) or die(mysqli_error());
    echo '

    Name
    Price
    Category

';

    if (mysqli_num_rows($result)>0)
    {
        while ($record = mysqli_fetch_array($result))
        {
            echo "
            $record[name]
            $record[price]
            $record[category_name]

";
        }
    }
    else
        echo "sikertelen";
?>

A: You should use inner join if the keys always match
SELECT * FROM products INNER JOIN category ON category.category_name=products.category_id

or left if the key don't match
SELECT * FROM products LEFT JOIN category ON category.category_name=products.category_id

If all the keys match the right join return nothings

A: You are joining on the wrong columns.  The NAME and the ID will likely not match.
$sql[0] = "SELECT * FROM products RIGHT JOIN category ON category.category_id=products.category_id";

I can tell this because you show the category_id in both tables.


text:
Q: Is there a Windows Form control that simulates SelectCheckBoxMenu control of Primefaces? Two year ago, I have developped a Java J2EE application using Primefaces widget.
Now, I develop an application using VB.Net using WinForms.
I search to use a widget that is equivalent to SelectCheckBoxMenu written by Primefaces for Web development www.primefaces.org/showcase
The particularity of this control is that it allows adding multiple keys from a ComboBox widget.
Example:

Do this control exist for WinForms ?
What is its name ?


text:
Q: Mathjax insert div write text ContentEditable div? i reference WYSIWYG Editor for Mathematical Equations using MathJax this Code
this code is here
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>mathjx</title>
    ;

<textarea id="wrapSelectedContent"></textarea>

<button onclick="wrapContent();">ConVert</button>

code is working very well.
now, I want change
<textarea id="wrapSelectedContent"> =>
 tag.
i change a div code. but script error.
"wh_test.html:27 Uncaught TypeError: selectedContent.setSelectionRange is not a function"
How does it work change this code.. Thanks for reading.

A: Firstly use the same ID in contenteditable div. Therefore
<textarea id="wrapSelectedContent"></textarea> needs to be changed into

 tag.
Secondly div has no value property you have to use innerHTML to get similar results as for textarea.
Thus following
var selectedContentValue = selectedContent.value.substring(start, end);
have to be changed into var selectedContentValue = selectedContent.innerHTML.substring(start, end);


text:
Q: Comparing IDataObject from the Clipboard My WPF application checks the data on the clipboard to see if it can work with the data or not. Because I set some buttons to be enabled/disabled based on the data (via an ICommand implementation), this code is called frequently.
The work to determine if my application can work with the data can be non-trivial at times, and thus is causing my application to "hang" randomly. I don't believe I can push this work off to another thread since the WPF runtime is expecting a response quickly.
In order to solve this issue, I thought I would compare the IDataObjects (the current one from the clipboard vs. a cached one from the previous attempt. A straight comparison (and even an object.ReferenceEquals does not return the desired results, so I thought I would try the method Clipboard.IsCurrent. The description sounds like exactly what I want, but when I evaluate the following:
Clipboard.IsCurrent(Clipboard.GetDataObject())

the result is false. The current workaround is to compare the data formats on the IDataObject, but that's not a good answer since my application can handle some files from the file system, but not all. So even though the formats are identical, the result on whether my application can handle the data may not always be the same.

A: Unfortunately, IsCurrent does not work in conjunction with GetDataObject. MSDN's description of OleIsCurrentClipboard (which IsCurrent uses internally) is quite explicit about this:
OleIsCurrentClipboard only works for the data object used in the OleSetClipboard function. It cannot be called by the consumer of the data object to determine if the object that was on the clipboard at the previous OleGetClipboard call is still on the clipboard.
A workaround could be to subscribe to clipboard updates (see e.g.
Clipboard event C#) and evaluate the data only when it changes, potentially in a background thread.


text:
Q: Many to Many relational data not showing in aws amplify dataStore data is poperly getting inserted. my problem is when i try fetch it does not provide me [Services] data.
schema.graphql
`
type Service @model @auth(rules: [{ allow: public }]) {
  id: ID!
  name: String!
  requestss: [Requests] @manyToMany(relationName: "RequestsService")
}

type Requests @model @auth(rules: [{ allow: public }, { allow: owner }]) {
  id: ID!
  requestType: String
  requestStatus: String
  preferredDateTime: AWSDateTime
  preferences: [String]
  Services: [Service] @manyToMany(relationName: "RequestsService")
}

`
model/index.d.ts
``
export declare class Requests
{ readonly id: string; readonly requestType?: string | null; readonly requestStatus?: string | null; readonly preferredDateTime?: string | null; readonly preferences?: (string | null)[] | null; readonly Services?: (RequestsService | null)[] | null; readonly createdAt?: string | null; readonly updatedAt?: string | null; constructor(init: ModelInit<Requests, RequestsMetaData>); static copyOf(source: Requests, mutator: (draft: MutableModel<Requests, RequestsMetaData>) => MutableModel<Requests, RequestsMetaData> | void): Requests;
}

export declare class Service { readonly id: string; readonly name: string; readonly createdAt?: string | null; readonly updatedAt?: string | null; readonly requestss?: (RequestsService | null)[] | null; constructor(init: ModelInit<Service, ServiceMetaData>); static copyOf(source: Service, mutator: (draft: MutableModel<Service, ServiceMetaData>) => MutableModel<Service, ServiceMetaData> | void): Service; }

export declare class RequestsService { readonly id: string; readonly service: Service; readonly requests: Requests; readonly createdAt?: string | null; readonly updatedAt?: string | null; constructor(init: ModelInit<RequestsService, RequestsServiceMetaData>); static copyOf(source: RequestsService, mutator: (draft: MutableModel<RequestsService, RequestsServiceMetaData>) => MutableModel<RequestsService, RequestsServiceMetaData> | void): RequestsService; }`

my insert query
import { DataStore } from "aws-amplify";
import { Requests, RequestsService } from "../models";
const newRequests = await DataStore.save(new Requests(request));
const newServices = [];
for (let service of services) {
  const newRequestService = await DataStore.save(
    new RequestsService({ service: service, requests: { id: newRequests.id } })
  );
  newServices.push(newRequestService.id);
}
console.log("newServices", newServices);
await DataStore.save(
  Requests.copyOf(newRequests, (updated) => {
    updated["Services"] = newServices;
  })
);

my get query
const existingRequests = await DataStore.query(Requests);
below is my response
{
  "_deleted": null,
  "_lastChangedAt": 1648815035648,
  "_version": 2,
  "createdAt": "2022-04-01T12:10:34.293Z",
  "id": "ec446c0f-5acd-4e6c-abd5-13e63faeaeca",
  "owner": "57853bc6-e4cf-4ad1-8ef8-2b0c200cc22f",
  "preferences": ["male"],
  "preferredDateTime": "2022-04-01T12:10:26.332Z",
  "requestStatus": "PENDING",
  "requestType": "PHYSIO",
  "updatedAt": "2022-04-01T12:10:34.293Z"
}

It should show in response like
Services:[ { id,service, requests } ]

A: I found one way to get response.
const getRequestById = await DataStore.query(Requests, id);
return new Promise(async (resolve, reject) => {
  let staffServices = [];
  const getServices = await DataStore.query(RequestsService, (c) =>
    c.service("eq", getRequestById.id)
  );
  if (getRequestById.Staff) {
    staffServices = await getStaffServiceById(getRequestById.Staff.id);
  }
  resolve({
    ...getRequestById,
    services: getServices,
    Staff: {
      ...getRequestById.Staff,
      services: staffServices,
    },
  });
})
  .then((promiseResp) => {
    return promiseResp;
  })
  .catch((err) => {
    return null;
  });

if any other solution is possible. please do ping here


text:
Q: Microsoft Visual Studio 2017 Enterprise Isolated Shell project template missing? Microsoft Visual Studio 2017 Enterprise Isolated Shell project template missing ?Any clue if i missed any extension pack pack or individual workload while installing ?

A: At the time of this writing (April 10, 2017) the Visual Studio 2017 Isolated / Integrated Shells haven't been announced yet. It seems that Microsoft will provide them but they need time to accommodate to the new Visual Studio 2017 internal component structure and setup. As you may know, Visual Studio 2017 doesn't use GAC or normal Windows Registry (it uses a private Registry hive) and its setup is based on workloads and very granular individual components. For example, the standalone Visual Studio 2017 Team Explorer was announced last week, weeks after the initial launch of Visual Studio 2017 RTM. With the Shells the same will happen eventually.

A: And now 3 years later (March 2020), it looks like Microsoft gave up on the Isolated Shell for Visual Studio. I could not find an official retirement of the software, however 2015 is the latest version I have found any reference to.

*

*http://www.visualstudioextensibility.com/2017/04/11/microsoft-the-visual-studio-shells-and-the-old-versions/

*https://visualstudio.microsoft.com/vs/older-downloads/isolated-shell/

*https://visualstudio.microsoft.com/vs/older-downloads/


text:
Q: ValueErrror unpack in Word2vec I have stopwords and list1 and want to get list 2 after removing stopwords
stopwords= [" I ", " in ", " a ", " m ", " of ", " It ", " is "," all ",  " about ", " you ", " to ", " at "]

list1 = ["I order food in a restaurant","I m fan of soccer","It is all about passion","you want to stay at home"]

list2 = [["order" "food","restaurant"],["fan","soccer"],["passion"],["want","stay","home"]

A: I don't know what your subject has to do with the code you're presenting, but here's a way to accomplish what you're asking for:
stopwords= [" I ", " in ", " a ", " m ", " of ", " It ", " is "," all ", " about ", " you ", " to ", " at "]

list1 = ["I order food in a restaurant","I m fan of soccer","It is all about passion","you want to stay at home"]

# remove spaces and lowerize each stop word
stopwords = [w.lower().strip() for w in stopwords]

# process each sentence, and for each sentence, each word
list2 = [[word for word in words.split() if word.lower() not in stopwords] for words in list1]

print(list2)

Result:
[['order', 'food', 'restaurant'], ['fan', 'soccer'], ['passion'], ['want', 'stay', 'home']]


text:
Q: python subprocess with hma I am trying to get subprocess to run an hma proxy through linux. I'm new to Python so maybe I'm not using the right approach. What I need it to do is run hma in the background and have the program check whether or not my public IP is the same as before the program was launched and if it isn't re-run the hma program every 30 minutes.
Basically the program needs to check current IP then connect to hma. If first IP matches second IP, i.e. hma hasn't connected, then print waiting. If the IP doesn't match then run hma again in 30 minutes. Here is the code I have so far.
import os
import webbrowser
import time
import socket
import urllib2
import subprocess

response = urllib2.urlopen("http://automation.whatismyip.com/n09230945.asp")
internal = response.read()
print "Internal IP Address is ", internal
hma = ['cd', '/Desktop/hma', ';', './hma-start', '-r']
subprocess.Popen(hma, shell=True)
response = urllib2.urlopen("http://automation.whatismyip.com/n09230945.asp")
external = response.read()
while (internal == external):
    time.sleep(1)
    response = urllib2.urlopen("http://automation.whatismyip.com/n09230945.asp")
    external = response.read()
    print 'waiting'

while (internal != external):
    print 'It changed'
    hma = ['cd', '/Desktop/hma', ';', './hma-start', '-r']
    subprocess.Popen(hma, shell=True)
    response = urllib2.urlopen("http://automation.whatismyip.com/n09230945.asp")
    external = response.read()

print "External IP Address is ", external

What am I doing wrong? Sorry if this is completely wrong. I'm new to the subprocess module

A: If you're using shell=True your commandline must be a string:
hma = 'cd /Desktop/hma; ./hma-start -r'
subprocess.Popen(hma, shell=True)

But you can also do this without shell=True:
hma = ['/Desktop/hma/hma-start', '-r']
subprocess.Popen(hma)

If you wanna wait until the process finished, call .communicate() on the Popen-Object.

A: Hi so I'm not familiar with hma, but something like this should work.
If not dav1d said make sure hma-start is in your path. I'm not quite sure why your using /Desktop/hma? It shouldn't matter where it is when you have elevated privs.
import os
import webbrowser
import time
import socket
import urllib2
import subprocess
import socket

URL = "http://automation.whatismyip.com/n09230945.asp"
DIR = '/Desktop/hma'
HMA = ['./hma-start', '-r']
WAIT_TIME = 60 * 30 # 30 min
GET_IP = lambda: urllib2.urlopen(URL).read()

if __name__ == '__main__':
    external = internal = GET_IP()
    print "Internal IP Address is %s" % internal
    try:
        os.chdir(DIR)
    except OSError:
        print "%s not found" % DIR

    print "External IP Address is ", external
    while True:
        external = GET_IP()
        if external != internal:
            print "Proxied"
            time.sleep(WAIT_TIME)
        else:
            print "Not Proxied"
            proc = subprocess.Popen(HMA)
            proc.wait()


text:
Q: How to change the colors value from theme.xml? I'm creating different themes for my application for different users and each one of them wants differents colors.
So, I have some defined groups of colors in my colors.xml and what I want to do is to change the value of those colors from my xml themes.
Right now I have the color.xml:

And then I have my theme.xml:

And what I'm doing to reach out to each one of the value name is declare them on attrs:

But it doesn't seem to work when I change the theme of the app in the manifest, so how can I change the colors value but not the name from my theme.xml.

A: Use:
public void onCreate(Bundle savedInstanceState) {
    setTheme(android.R.style.Theme);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
}

to set theme.


text:
Q: IIS browse web site list In Windows server 2008, how do I get list of browse web sites in IIS 7?

A:
To view a list of sites on a Web server
To Use the UI

*

*Open IIS Manager. For information about opening IIS Manager, see
  Open IIS Manager (IIS 7). For information about navigating to
  locations in the UI, see Navigation in IIS Manager (IIS 7).

*In the Connections pane, click Sites in the tree.

*View the list of sites or click a site in the list to modify site
  properties from the Actions pane.

   Command Line
To view a list of sites, type the following at the command prompt, and
  then press ENTER:
appcmd list site

To view a list of sites on the Web server that have a specific
  setting, you can filter the list results by including criteria on
  which to filter the results of the command. To do this, use the
  following syntax:
appcmd list site / attribute : value

The variables attribute and value are the criteria on which you want
  to filter the results. For example, you might have two sites that use
  the same binding, which prevents them from running at the same time.
  You can view a list of sites that use that binding by filtering the
  results. To return a list of results filtered by sites that use the
  HTTP protocol, and that listen for all IP addresses on port 80 without
  a host header, type the following at the command prompt, and then
  press ENTER:
appcmd list site /bindings:http/*:80:

For more information about Appcmd.exe, see Appcmd.exe (IIS
  7).
WMI
Use the following WMI classes, methods, or properties to perform this
  procedure:

*

*ServerContainsSite class

*Site class

  For more information about WMI and IIS, see Windows Management
  Instrumentation (WMI) in IIS
  7.
  For more information about the classes, methods, or properties
  associated with this procedure, see the IIS WMI Provider
  Reference on the MSDN
  site.
source


text:
Q: How to resolve invalid connect parameters in jms? I am using ActiveMQ to transfer data objects from client to server by using following client uri :
ssl://X.X.X.X:61616?useKeepAlive=false&wireFormat.maxInactivityDuration=30000&wireFormat.cacheEnabled=false&wireFormat.tightEncodingEnabled=true

By using the above uri am getting the following exception when I start the application :
javax.jms.JMSException: Could not create Transport. Reason: java.lang.IllegalArgumentException: Invalid connect parameters: {useKeepAlive=false}
        at org.apache.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:35)
        at org.apache.activemq.ActiveMQConnectionFactory.createTransport(ActiveMQConnectionFactory.java:245)
        at org.apache.activemq.ActiveMQConnectionFactory.createActiveMQConnection(ActiveMQConnectionFactory.java:258)
        at org.apache.activemq.ActiveMQConnectionFactory.createActiveMQConnection(ActiveMQConnectionFactory.java:230)
        at org.apache.activemq.ActiveMQConnectionFactory.createConnection(ActiveMQConnectionFactory.java:178)
        at com.infomindz.esdms.messaging.agent.job.handler.MessageQueueLocator.getSecureManagementJmsSession(MessageQueueLocator.java:991)
        at com.infomindz.esdms.messaging.agent.job.handler.MessageQueueLocator.sendMessageToSEMQueue(MessageQueueLocator.java:902)
        at com.infomindz.esdms.messaging.agent.job.MediaDriverStatusJob.saveAndSendPropertyDetails(Unknown Source)
        at com.infomindz.esdms.messaging.agent.job.MediaDriverStatusJob.checkInitFile(Unknown Source)
        at com.infomindz.esdms.messaging.agent.job.MediaDriverStatusJob.execute(Unknown Source)
        at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
        at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:529)
    Caused by: java.lang.IllegalArgumentException: Invalid connect parameters: {useKeepAlive=false}
        at org.apache.activemq.transport.TransportFactory.doConnect(TransportFactory.java:144)
        at org.apache.activemq.transport.TransportFactory.doConnect(TransportFactory.java:51)
        at org.apache.activemq.transport.TransportFactory.connect(TransportFactory.java:80)
        at org.apache.activemq.ActiveMQConnectionFactory.createTransport(ActiveMQConnectionFactory.java:243)

How do I resolve this exception?

A: Transport parameters must be prefixed with "transport." in the url; so you need to do it like this :
ssl://X.X.X.X:61616?transport.useKeepAlive=false

See this page.


text:
Q: Replicating elements in numpy array I have a numpy array say
a = array([[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]])

I have an array 'replication' of the same size where replication[i,j](>=0) denotes how many times a[i][j] should be repeated along the row. Obiviously, replication array follows the invariant that np.sum(replication[i]) have the same value for all i.
For example, if
replication = array([[1, 2, 1],
                     [1, 1, 2],
                     [2, 1, 1]])

then the final array after replicating is:
new_a = array([[1, 2, 2, 3],
           [4, 5, 6, 6],
           [7, 7, 8, 9]])

Presently, I am doing this to create new_a:
 ##allocate new_a
 h = a.shape[0]
 w = a.shape[1]
 for row in range(h):
      ll = [[a[row][j]]*replicate[row][j] for j in range(w)]
      new_a[row] = np.array([item for sublist in ll for item in sublist])

However, this seems to be too slow as it involves using lists. Can I do the intended entirely in numpy, without the use of python lists?

A: You can flatten out your replication array, then use the .repeat() method of a:
import numpy as np

a = array([[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]])

replication = array([[1, 2, 1],
                     [1, 1, 2],
                     [2, 1, 1]])

new_a = a.repeat(replication.ravel()).reshape(a.shape[0], -1)

print(repr(new_a))
# array([[1, 2, 2, 3],
#        [4, 5, 6, 6],
#        [7, 7, 8, 9]])


text:
Q: Displaying Numeric Pagination vs. Previous and Next Links in WordPress? By default, WordPress shows previous and next links when content is split onto different pages. Is there a way to get it to use proper pagination (with numbers), perhaps with a plugin?

A: yes,
try wp-pagenavi
http://wordpress.org/extend/plugins/wp-pagenavi/

A: Add to Functions.php
/* Numeric Pagination ********************************************/

function numeric_pagination ($pageCount = 9, $query = null) {

    if ($query == null) {
        global $wp_query;
        $query = $wp_query;
    }

    if ($query->max_num_pages <= 1) {
        return;
    }

    $pageStart = 1;
    $paged = $query->query_vars['paged'];

    // set current page if on the first page
    if ($paged == null) {
        $paged = 1;
    }

    // work out if page start is halfway through the current visible pages and if so move it accordingly
    if ($paged > floor($pageCount / 2)) {
        $pageStart = $paged - floor($pageCount / 2);
    }

    if ($pageStart < 1) {
        $pageStart = 1;
    }

    // make sure page start is
    if ($pageStart + $pageCount > $query->max_num_pages) {
        $pageCount = $query->max_num_pages - $pageStart;
    }

?>

<?php
    if ($paged != 1) {
?>
    <a href="<?php echo get_pagenum_link(1); ?>" class="numbered page-number-first">‹ <?php _e('<< First', 'global'); ?>
<?php
    }
    // first page is not visible...
    if ($pageStart > 1) {
        //echo 'previous';
    }
    for ($p = $pageStart; $p <= $pageStart + $pageCount; $p ++) {
        if ($p == $paged) {
?>
        <span class="numbered page-number-<?php echo $p; ?> current-numeric-page"><?php echo $p; ?>
<?php } else { ?>
        <a href="<?php echo get_pagenum_link($p); ?>" class="numbered page-number-<?php echo $p; ?>"><?php echo $p; ?>

<?php
        }
    }
    // last page is not visible
    if ($pageStart + $pageCount < $query->max_num_pages) {
        //echo "last";
    }
    if ($paged != $query->max_num_pages) {
?>
        <a href="<?php echo get_pagenum_link($query->max_num_pages); ?>" class="numbered page-number-last"><?php _e('>> Last', 'global'); ?> ›
<?php } ?>

<?php } ?>

Before The Loop
<?php
$page = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts("showposts=6&paged=$page");
?>

After The Loop Between endwhile and else
<?php numeric_pagination(); ?>


text:
Q: Read large PUT or POST request body as a stream in Rails without buffering to disk I am experimenting with Rails 6 for an API use case. Users would post large requests which rails would receive and stream to another place. This would probably run with JRuby, but right now I am testing with MRI Ruby. The webserver is Puma (out of the box rails install).
Is there any way to read the request body as a stream as it is uploaded, or does Rails need to wait for the entire request to upload before it can access it?
Using this Curl command:
curl  -i -X PUT -T data.bin "http://localhost:3000/welcome/stream"

And this simple controller:
  def stream
    puts "The stream was called"

    io = request.body
    until io.eof?
      io.read(1024*1024)
      puts "Read 1MB"
    end

    head 200, content_type: "text/html"
  end

It seems as though the entire request is staged somewhere before rails get access to it, as there is a long delay before any of my puts appear in the console.
Searching a bit, it seems it may be the websever (Puma, Unicorn, etc) that buffers the data and it only invokes Rails when all the data has been received.
Is there anyway to start reading the stream as it comes in and or avoid buffering it?
Is it Rack or Puma which does the buffering? If so, where does it buffer the data?

A:
Is it Rack or Puma which does the buffering? If so, where does it buffer the data?

The server collects the whole stream before passing it onwards to Rack / Rails... so you won't be able to start handling the request before the body completely uploads.
There's a good reason for this design, as the server will use the available threads to poll the IO instead of blocking, allowing your application to process other requests while performing the IO operations in the background.
Otherwise the IO would block the thread (and, by extension, the server) when your application called read on an incomplete stream, causing concurrency to falter.

Is there anyway to start reading the stream as it comes in and or avoid buffering it?

You can either implement your own server (not recommended), or upload bits and pieces using AJAX / WebSockets (a more common approach).


text:
Q: kendojs mobile - how do i bind to a data-title? I have a drawer-layout

I would like to bind to the data-title attribute but I can not figure out how to do this.
My DataSource looks like this:
    var app = new kendo.mobile.Application(document.body);
var dataOrg = new kendo.data.DataSource({
    transport: {
        read: {
            type: "GET",
            url: "http://webapi.dynacalbeta.com/api/org?DynaCalPath=" + urlParams['Org'],
            dataType: "jsonp",
            contentType: "application/json; charset=utf-8",
            cache: false,
            data: {}
        }
    },
    error: function (e, a, b) {
        console.log("Error:" & e & a & b);
    },
    success: function (obj, txt, xhr) {
        console.log("Success:" & txt);
    }
});

I want the data-title to be filled with {data.Name}
Thanks for any help.
Shawn


text:
Q: Why valueChanges does not work in my code? I have a MatTableDataSource that shows some elements retrieved from my MongoDB and I want to filter each column of the table in order to have only what matches my input.
This is my code:
datatable.component.ts
export class DatatableComponent implements OnInit {

 @ViewChild(MatPaginator) paginator: MatPaginator;

 pratiche: any;
 displayedColumns: string[] = ['idPratica', 'barcode', 'status', 'firstName', 'lastName', 'fiscalCode', 'pratica'];
 dataSource = new MatTableDataSource(this.pratiche);
 idFilter = new FormControl('');
 barcodeFilter = new FormControl('');

 filterValues = {
 id: '',
 barcode: '',
 };

 constructor(private praticaService: PraticaService) {
 this.dataSource.data = this.pratiche;
 this.dataSource.filterPredicate = this.createFilter();
 }

 async ngOnInit() {
  const res = await this.praticaService.getAllPratiche();
  this.pratiche = res.data;
  this.dataSource = new MatTableDataSource(this.pratiche);
  this.dataSource.paginator = this.paginator;

  this.idFilter.valueChanges
   .subscribe(
     id => {
       this.filterValues.id = id;
       this.dataSource.filter = JSON.stringify(this.filterValues);
     }
  )
  this.barcodeFilter.valueChanges
   .subscribe(
     barcode => {
      this.filterValues.barcode = barcode;
      this.dataSource.filter = JSON.stringify(this.filterValues);
    }
  )
 }

  createFilter(): (data: any, filter: string) => boolean {
   let filterFunction = function (data, filter): boolean {
   let searchTerms = JSON.parse(filter);
   return data.id.toLowerCase().indexOf(searchTerms.id) !== -1
    && data.barcode.toLowerCase().indexOf(searchTerms.barcode) !== -1
    && data.status.toLowerCase().indexOf(searchTerms.status) !== -1
    && data.firstName.toLowerCase().indexOf(searchTerms.firstName) !== -1
    && data.lastName.toLowerCase().indexOf(searchTerms.lastName) !== -1
    && data.fiscalCode.toLowerCase().indexOf(searchTerms.fiscalCode) !== -1;
 }
 return filterFunction;
 }
}

datatable.component.html

<ng-container matColumnDef="idPratica">

    ID Pratica
    <mat-form-field class="filter" floatLabel="never">
      <mat-label></mat-label>
      <input matInput [formControl]="idFilter">
    </mat-form-field>

  {{element.id}}
</ng-container>

<ng-container matColumnDef="barcode">

    Barcode
    <mat-form-field class="filter" floatLabel="never">
      <mat-label></mat-label>
      <input matInput [formControl]="barcodeFilter">
    </mat-form-field>

  {{element.barcode}}
</ng-container>

pratica.service.ts
public getAllPratiche(): Promise<any> {
    const url = "http://127.0.0.1:3001/pratiche/getPratiche";
    return new Promise((resolve, reject) => {
        this.http.get(url, { responseType: "json", observe: "response" })
            .pipe(map((response: any) => response))
            .subscribe(res => {
                if (res.error) {
                    reject(res.error);
                } else {
                    resolve(res.body);
                }
            }, err => {
                reject(err)
            });
    });
}

I retrieve correctly my data from my MongDb but when I try to filter it, nothing happens. I'm new on angular and probably I am making mistakes on Promise vs Observable. Any suggestion?


text:
Q: Device ID Error we had set up a app in mobile push, however, when a new applier install the app, the contact shows in all contact including wrong device ID which it's actually contains in system token.
Not sure how can we adjust the code.
We had follow the instruction from mobile push document.
Many Thanks!

A: @victoria, are you using the MobilePush SDK? If so, what platform & version are you implementing?
The deviceId value is automatically generated as a unique identifier by the SDK and sent to the server for association with the contact. It is an internal value.
A system token is generated and passed by your application code to the SDK.
Does your application call our setContactKey() method? Is that using a unique value per device/user?
If necessary, I suggest you open a support case with your Marketing Cloud rep so that we @murilo, in addition to gathering the information Seth has requested, please be sure to log a support request with your Marketing Cloud representative.
We will be much better able to track, respond and be held accountable to you (and all our customers) needs via customer support.
Of course, continue to raise questions and concerns here - the MobilePush SDK team is happy to help in any way we can.


text:
Q: Error while installing Cordova I am getting this error while installing Cordova:

npm http GET https://registry.npmjs.org/cordova
npm http GET https://registry.npmjs.org/cordova
npm http GET https://registry.npmjs.org/cordova
npm ERR! Error: CERT_UNTRUSTED*
npm ERR!     at SecurePair. (tls.js:1370:32)
npm ERR!     at SecurePair.EventEmitter.emit (events.js:92:17)
npm ERR!     at SecurePair.maybeInitFinished (tls.js:982:10)
npm ERR!     at CleartextStream.read [as _read] (tls.js:469:13)
npm ERR!     at CleartextStream.Readable.read (_stream_readable.js:320:10)
npm ERR!     at EncryptedStream.write [as _write] (tls.js:366:25)
npm ERR!     at doWrite (_stream_writable.js:223:10)
npm ERR!     at writeOrBuffer (_stream_writable.js:213:5)
npm ERR!     at EncryptedStream.Writable.write
(_stream_writable.js:180:11)
npm ERR!     at write (_stream_readable.js:583:24)
Please tell the cause of this error and how I can remove it.

A: Your version of npm is not up to date, so you cannot install Cordova until you successfully update it. After your npm is updated to npm 6.1.0 Cordova can be installed successfully. The best way to update npm is to install the node snap package which has npm bundled with it, and then update npm with sudo npm i npm.

Node.js is available as a snap package in all currently supported versions of Ubuntu. Specific to Node.js, developers can choose from one of the currently supported releases and get regular automatic updates directly from NodeSource. Node.js versions 6, 8, 9, 10, 11, 13, 14, 15, 16, 17 and 18 are currently available, with the Snap Store being updated within hours or minutes of a Node.js release.
Node can be installed with a single command, for example:
sudo snap install node --classic --channel 11/stable

The node snap can be accessed by the command node, for example:
$ node -v
v11.5.0
An up-to-date version of npm will installed as part of the node snap. npm should be run outside of the node repl, in your normal shell. After installing the node snap run the following command to enable npm update checking:
sudo chown -R $USER:$(id -gn $USER) /home/your-username/.config
Replace  your-username in the above command with your own username. Then run npm -v to check if the version of npm is up-to-date. As an example I checked that npm was up-to-date, checked the version of an already installed package named yarn with the command npm list yarn and then updated the existing yarn package to the latest version with the command npm update yarn
Users can switch between versions of Node.js at any time without needing to involve additional tools like nvm (Node Version Manager), for example:
sudo snap refresh node --channel=10/stable

Users can test bleeding-edge versions of Node.js that can be installed from the latest edge channel by switching with:
sudo snap switch node --edge

This approach is only recommended for those users who are willing to participate in testing and bug reporting upstream.
Node.js LTS schedule

Release
Status
Codename
Initial release
LTS Start
Maintenance Start
Maintenance End

6.x
EOL
Boron
2016-04-26
2016-10-18
2018-04-30
2019-04-30

7.x
EOL

2017-05-30

2017-06-30

8.x
EOL
Carbon
2016-10-25
2017-10-31
2019-01-01
2019-12-31

9.x
EOL

2017-10-01

2018-06-30

10.x
EOL
Dubnium
2018-04-24
2018-10-30
2020-05-19
2021-04-30

11.x
EOL

2018-10-23

2019-06-01

12.x
Maintenance LTS
Erbium
2019-04-23
2019-10-21
2020-11-301
2022-04-30

13.x
EOL

2019-10-22

2020-06-01

14.x
Maintenance LTS
Fermium
2020-04-21
2020-10-27
2021-10-30
2023-04-30

16.x
Active LTS
Gallium
2021-04-20
2021-10-26
2022-10-18
2024-04-30

17.x
Current

2021-10-19

2022-04-01
2022-06-01

18.x
Current

2022-04-19
2022-10-25
2023-10-18
2025-04-30


text:
Q: Can VHDL alias be created to contain several different concatenated std_logic_vectors? The alias is basically an alternative name for something. Now assume that I want to create alternative name for a bunch of things like this:
alias myalias : std_logic_vector(7 downto 0) is a(3 downto 0) & b(1 downto 0) & c & d;

Is this allowed in VHDL? From my understanding, it is not.

A: Isn't this just a wire?
entity Whatever is port (
  a : in std_logic_vector(32 downto 0);
  b : in std_logic_vector(32 downto 0);
  c : in std_logic,
  d : in std_logic);
end Whatever;

architecture x of Whatever is
  signal myalias : std_logic_vector(7 downto 0);
begin
  myalias <= a(3 downto 0) & b(1 downto 0) & c & d;
end x;


text:
Q: Extract ddl for alter statement in oracle I'm working on an automation to generate the ddl automatically.
Ofcourse I'm using DBMS_METADATA.GET_DDL to get the same. It works fine. Now I need help on the following.
Assume TableA is already there in the database with three column COLA,COLB & COLC
Lets say I've modified the table by adding another column COLD
Now I wanted to generate the below script automatically,
ALTER TABLE TABLEA ADD COLUMN COLD VARCHAR2(100);

Suggest me a way to accompolish the same.

A: DBMS_METADATA_DIFF generates DDL difference scripts.
create user test_user1 identified by test_user1;
create user test_user2 identified by test_user2;

create table test_user1.tablea(cola number, colb number, colc number);
create table test_user2.tablea(cola number, colb number, colc number
    ,cold varchar2(100));

select
    dbms_metadata_diff.compare_alter(
        object_type => 'TABLE',
        name1 =>       'TABLEA',
        name2 =>       'TABLEA',
        schema1 =>     'TEST_USER1',
        schema2 =>     'TEST_USER2'
    ) alter_ddl
from dual;

ALTER_DDL
---------
ALTER TABLE "TEST_USER1"."TABLEA" ADD ("COLD" VARCHAR2(100))

That's a technical solution.  From a process perspective, I agree with a_horse_with_no_name that it's generally better to hand-code those things and use version control.  However, in practice, database programmers rarely use version control in a meaningful way.  I don't expect you to suddenly switch methods, but do consider that approach when the next project starts.


text:
Q: What do "!" and "*" mean in the password section in /etc/shadow? In a /etc/shadow file, it looks like as follows.
root:!:15764:0:99999:7:::
daemon:*:15749:0:99999:7:::

What do these characters ("!" and "*") mean in the password section?

A: From the manual page shadow(5):

encrypted password
  Refer to crypt(3) for details on how this string is interpreted.
If the password field contains some string that is not a valid result
  of crypt(3), for instance ! or *, the user will not be able to use a
  unix password to log in (but the user may log in the system by other
  means).
This field may be empty, in which case no passwords are required to
  authenticate as the specified login name. However, some applications
  which read the /etc/shadow file may decide not to permit any access at
  all if the password field is empty.
This field may be empty, in which case no passwords are required to
  authenticate as the specified login name. However, some applications
  which read the /etc/shadow file may decide not to permit any access at
  all if the password field is empty.

Also, the program passwd (see passwd(1)) can be locked to create these locked accounts by prefixing the password with !:

-l, --lock
  Lock the password of the named account. This option disables a
  password by changing it to a value which matches no possible encrypted
  value (it adds a '!' at the beginning of the password).

A: man shadow
   If the password field contains some string that is not a valid
   result of crypt(3), for instance ! or *, the user will not be able
   to use a unix password to log in (but the user may log in the
   system by other means).

   This field may be empty, in which case no passwords are required to
   authenticate as the specified login name. However, some
   applications which read the /etc/shadow file may decide not to
   permit any access at all if the password field is empty.

   A password field which starts with a exclamation mark means that
   the password is locked. The remaining characters on the line
   represent the password field before the password was locked.

So * means no password can be used to access the account, and ! means its locked

A: Maybe, that ! is account with root privileges, and * is for daemons.
Also ! or * indicate that the user will not be able to use a Unix/Linux password to log in. In other words user login will be disabled.
More here:
http://www.cyberciti.biz/faq/understanding-etcshadow-file/


text:
Q: Why is Haskell/unpack messing with my bytes? I've built a tiny UDP/protobuf transmitter and receiver.  I've spent the morning trying to track down why the protobuf decoding was producing errors, only to find that it was the transmitter (Spoke.hs) which was sending incorrect data.
The code used unpack to turn Lazy.ByteStrings into Strings that the Network package will send.  I found unpack in Hoogle.  It may not be the function I'm looking for, but its description looks suitable:  "O(n) Converts a ByteString to a String."
Spoke.hs produces the following output:
chris@gigabyte:~/Dropbox/haskell-workspace/hub/dist/build/spoke$ ./spoke
45
45
["a","8","4a","6f","68","6e","20","44","6f","65","10","d2","9","1a","10","6a","64","6f","65","40","65","78","61","6d","70","6c","65","2e","63","6f","6d","22","c","a","8","35","35","35","2d","34","33","32","31","10","1"]

While wireshark shows me that the data in the packet is:
0a:08:4a:6f:68:6e:20:44:6f:65:10:c3:92:09:1a:10:6a:64:6f:65:40:65:78:61:6d:70:6c:65:2e:63:6f:6d:22:0c:0a:08:35:35:35:2d:34:33:32:31:10

The length (45) is the same from Spoke.hs and Wireshark.
Wireshark is missing the last byte (value Ox01) and a stream of central values is different (and one byte larger in Wireshark).
"65","10","d2","9" in Spoke.hs vs 65:10:c3:92:09 in Wireshark.
As 0x10 is DLE, it struck me that there's probably some escaping going on, but I don't know why.
I have many years of trust in Wireshark and only a few tens of hours of Haskell experience, so I've assumed that it's the code that's at fault.
Any suggestions appreciated.
-- Spoke.hs:

module Main where

import Data.Bits
import Network.Socket -- hiding (send, sendTo, recv, recvFrom)
-- import Network.Socket.ByteString
import Network.BSD
import Data.List
import qualified Data.ByteString.Lazy.Char8 as B
import Text.ProtocolBuffers.Header (defaultValue, uFromString)
import Text.ProtocolBuffers.WireMessage (messageGet, messagePut)
import Data.Char (ord, intToDigit)
import Numeric

import Data.Sequence ((><), fromList)

import AddressBookProtos.AddressBook
import AddressBookProtos.Person
import AddressBookProtos.Person.PhoneNumber
import AddressBookProtos.Person.PhoneType

data UDPHandle =
     UDPHandle {udpSocket  :: Socket,
                udpAddress :: SockAddr}
opensocket :: HostName             -- ^ Remote hostname, or localhost
           -> String               -- ^ Port number or name
           -> IO UDPHandle         -- ^ Handle to use for logging
opensocket hostname port =
    do -- Look up the hostname and port.  Either raises an exception
       -- or returns a nonempty list.  First element in that list
       -- is supposed to be the best option.
       addrinfos <- getAddrInfo Nothing (Just hostname) (Just port)
       let serveraddr = head addrinfos

       -- Establish a socket for communication
       sock <- socket (addrFamily serveraddr) Datagram defaultProtocol

       -- Save off the socket, and server address in a handle
       return $ UDPHandle sock (addrAddress serveraddr)

john = Person {
  AddressBookProtos.Person.id = 1234,
  name = uFromString "John Doe",
  email = Just $ uFromString "jdoe@example.com",
  phone = fromList [
    PhoneNumber {
      number = uFromString "555-4321",
      type' = Just HOME
    }
  ]
}

johnStr = B.unpack (messagePut john)

charToHex x = showIntAtBase 16 intToDigit (ord x) ""

main::IO()
main =
    do udpHandle <- opensocket "localhost" "4567"
       sent <- sendTo (udpSocket udpHandle) johnStr (udpAddress udpHandle)
       putStrLn $ show $ length johnStr
       putStrLn $ show sent
       putStrLn $ show $ map charToHex johnStr
       return ()

A: The documentation I see for the bytestring package lists unpack as converting a ByteString to [Word8], which is not the same as a String. I would expect some byte difference between ByteString and String because String is Unicode data while ByteString is just an efficient array of bytes, but unpack shouldn't be able to produce a String in the first place.
So you're probably falling foul of Unicode conversion here, or at least something's interpreting it as Unicode when the underlying data really isn't and that seldom ends well.

A: I think you'll want toString and fromString from utf8-string instead of unpack and pack. This blog post was very helpful for me.


text:
Q: how to put 2 layouts on top of each others I'm trying to put 2 layouts on top of each others but it doesn't work.There is a space that i don't know how to remove.
here is my code:
<LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_gravity="bottom|center"
                android:weightSum="1">

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="170dp"
                    android:layout_weight="0.5"
                    android:background="@drawable/column_white"
                    android:layout_gravity="bottom|center"
                    android:gravity="bottom"
                    android:orientation="vertical"

                    >
                    <LinearLayout
                        android:layout_width="10sp"
                        android:layout_height="100sp"
                        android:background="@drawable/arrow_body"
                        android:layout_marginLeft="10sp"
                        ></LinearLayout>
                    <LinearLayout
                       android:layout_width="wrap_content"
                       android:layout_height="wrap_content"
                       android:background="@drawable/arrow_shape"
                        android:layout_marginLeft="6sp"
                        ></LinearLayout>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="150dp"
                    android:layout_margin="25sp"
                    android:background="@drawable/column_blue"
                    android:gravity="center"
                    android:layout_weight="0.5" >

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="40 000 "
                        android:textColor="#ffffff"
                        android:textSize="25sp" />
                </LinearLayout>

            </LinearLayout>

with RelativeLayout:
<RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="170dp"
        android:background="@drawable/column_white"
        android:gravity="bottom"

        android:layout_alignBottom="@id/second_part"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="10sp"
            android:layout_height="100sp"
            android:layout_marginLeft="10sp"
            android:background="@drawable/arrow_body" >
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="6sp"
            android:background="@drawable/arrow_shape" >
        </LinearLayout>

    </LinearLayout>

    <LinearLayout

        android:id="@+id/second_part"
        android:layout_width="wrap_content"
        android:layout_height="150dp"
        android:layout_margin="25sp"

        android:background="@drawable/column_blue"
        android:gravity="center" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="40 000"
            android:textColor="#ffffff"
            android:textSize="25sp" />
    </LinearLayout>
</RelativeLayout>

A: Use Relative layout to place views on top of each other , like this
 <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center"
        android:background="#f00"
        android:orientation="vertical"
        android:weightSum="1" >

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="170dp"
            android:layout_centerInParent="true"
            android:layout_gravity="bottom|center"
            android:background="#fff"
            android:gravity="bottom"
            android:orientation="vertical" >

            <LinearLayout
                android:layout_width="10dp"
                android:layout_height="100sp"
                android:layout_centerInParent="true"
                android:layout_marginLeft="10sp"
                android:background="#37c100" >
            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="6sp"
                android:background="@drawable/arrow_shape" >
            </LinearLayout>
        </RelativeLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="150dp"
            android:layout_centerInParent="true"
            android:layout_margin="25sp"
            android:layout_weight="0.5"
            android:background="#0000ff"
            android:gravity="center" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="40 000 "
                android:textColor="#ffffff"
                android:textSize="25sp" />
        </LinearLayout>
    </RelativeLayout>

A: In your second LinearLayout, you have a android:layout_margin="25sp".
Remove this line or at least don't set a marginTop.

A: This can now also be done using a constraintlayout. In my use case I had a RecyclerView that when empty had to be "covered" by a text and a button to allow users to add items to the list. (Part of the Big Nerd Ranch programming book, challenge 13.3)
Code is as follows (change to your own needs):
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/no_crimes_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/no_crimes_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:text="@string/no_crimes"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="@+id/recyclerView"
            app:layout_constraintStart_toStartOf="@+id/recyclerView"
            app:layout_constraintTop_toTopOf="@+id/recyclerView" />

        <Button
            android:id="@+id/new_crime_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:text="@string/new_crime"
            app:layout_constraintBottom_toBottomOf="@+id/recyclerView"
            app:layout_constraintEnd_toEndOf="@+id/recyclerView"
            app:layout_constraintStart_toStartOf="@+id/recyclerView"
            app:layout_constraintTop_toBottomOf="@+id/textView" />

    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/crime_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>


text:
Q: Users in subsite are unable to access despite having "Contribute" Access We have an Audit site and within that we have a Findings subsite.  There is a group with contributor access to this subsite called Findings Contributors, and they do NOT have access to the main site.
For some strange reason, they're unable to access the subsite.  Does anyone know why this group might not be able to access the subsite?

Access Denied. Exception: Access is denied. (Exception from HRESULT:
  0x80070005 (E_ACCESSDENIED)), StackTrace:   at
  Microsoft.SharePoint.Library.SPRequestInternalClass.GetListsWithCallback(String
  bstrUrl, Guid foreignWebId, String bstrListInternalName, Int32
  dwBaseType, Int32 dwBaseTypeAlt, Int32 dwServerTemplate, UInt32
  dwGetListFlags, UInt32 dwListFilterFlags, Boolean bPrefetchMetaData,
  Boolean bSecurityTrimmed, Boolean bGetSecurityData, Boolean
  bPrefetchRelatedFields, ISP2DSafeArrayWriter p2DWriter, Int32&
  plRecycleBinCount)
      at Microsoft.SharePoint.Library.SPRequest.GetListsWithCallback(String
  bstrUrl, Guid foreignWebId, String bstrListInternalName, Int32
  dwBaseType, Int32 dwBaseTypeAlt, Int32 dwServerTemplate, UInt32
  dwGetListFlags, UInt32 dwListFilterFlags, Boolean bPrefetchMetaData,
  Boolean bSecurityTrimmed, Boolean bGetSecurityData, Boolean
  bPrefetchRelatedFields, ISP2DSafeArrayWriter p2DWriter, Int32&
  plRecycleBinCount).   f7f92c9d-b400-6057-49ef-a8b3f8d19374

A: Make sure they still have "Limited Access" permission in the root site. This should be assigned automatically by SharePoint but something to check.
what is limited access?
In SP2013 you won't see Limited Access on the permission pages. The Sharegate article above says you will see this message but I have not been able to get that to work:

"There are limited access users on this site. Users may have limited access if an item or document under the site has been shared with them".

Instead, you can use Powershell to verify that Limited Access is being granted as expected.
$web = Get-SPWeb <web url>
$web.RoleAssignments | ft Member,RoleDefinitionBindings

If you don't see the permissions you expect, I would try removing the permissions and reassign them in the subsite. This should make SharePoint grant limited access at the root. I've tested this in my environment. I have a list with broken inheritance. When I assign a user permissions to this list, that user is granted Limited Access at the root.

A: This site shows the permissions that should be checked in the Contribute permission level.
Go to permission levels on your Sharepoint account, click on Contribute and make sure that those permissions under Contribute permission level is checked.


text:
Q: Select a key value from MySQL table where one row with the key is greater than another So assume I have this table:
+-------+-------+--------+--------+
|  key  |  id   |  type  |  value |
+-------+-------+--------+--------+
|   1   |   1   |  cool  |    5   |
|   2   |   1   |  uncool|    10  |
|   3   |   2   |  none  |    7   |
|   4   |   2   |  cool  |    23  |
|   5   |   2   |  uncool|    4   |
|   6   |   3   |  cool  |    6   |
|   7   |   3   |  uncool|    3   |
|   8   |   3   |  unapp |    52  |
+-------+-------+--------+--------+

Note that the key column is just the unique identifier, and is not relevant for what I am trying to do.
I want to find the ids (key) where the cool type value is greater than the uncool type value, ignoring any other rows.
So the result would be
+------+
|  id  |
+------+
|  2   |
|  3   |
+------+

I spent a few hours with the SQL editor open, messing with HAVING and GROUP BY and haven't been able to find a solution.
Is there a way to do this without resorting to making queries and then performing checks in another language, or is this the only solution?

A: You can group by the  id and take only those having the condition you describe.
select id
from your_table
group by id
having max(case when `type` = 'cool' then `value` end) >
       max(case when `type` = 'uncool' then `value` end)

A: SELECT t1.id
FROM table t1
LEFT JOIN table t2 ON t1.id = t2.id
                  AND t2.type = 'uncool'
WHERE t1.type = 'cool'
  AND (t1.value > t2.value OR t2.value IS NULL)

fiddle
If uncool is not present (for example, remove row with key=5) then my solution will give 2 rows whereas another solutions will give 1 row only.


text:
Q: SQL: Inserting all possible pairs from two parameter lists I have a table in a MySQL database which relates items and tags, with columns item_id, tag_id. I need to write a query which receives a list of items and a list of tags and applies each tag to each item.
My current implementation looks like this:
INSERT INTO item_tag (item_id, tag_id)
  (SELECT tag.tag_id, item.item_id FROM tag, item
  WHERE tag.tag_id in (:tags)
   AND  item.item_id in (:items))

And this works but it's hacky and inneficient, I'm querying the tag and item tables to fetch values I already have in the parameters (and I already know at this point those are valid ids, so I don't really need to check for existence).
Is there a cleaner way to do this? For example I think of something like (psuedo code):
SELECT * FROM all_values_in_a_column(:tags)
JOIN all_values_in_a_column(:items)