text:
Q: add n working days including custom holiday list in oracle plsql I need to find the 'n'th business day in oracle plsql function which should exclude weekends and custom list of holidays. I got something like this however unable to fit the custom holiday logic in here,
create or replace function add_n_working_days (
  start_date date, working_days pls_integer
) return date as
  end_date date := start_date;
  counter  pls_integer := 0;
begin

  if working_days = 0 then
    end_date := start_date;
  elsif to_char(start_date, 'fmdy') in ('sat', 'sun') then
    end_date := next_day(start_date, 'monday');
  end if;

  while (counter < working_days) loop
    end_date := end_date + 1;
    if to_char(end_date, 'fmdy') not in ('sat', 'sun') then
      counter := counter + 1;
    end if;
  end loop;

  return end_date;

end add_n_working_days;
/

I have the custom holiday list in a different table which can be extracted using the sql
select holidays from holiday_table

I tried adding elsif condition with a sub query but that is not supported
if to_char(end_date, 'fmdy') not in ('sat', 'sun') then
      counter := counter + 1;
elsif to_char(end_date, 'YYYYMMDD') in (select holidays from holiday_table) then
      counter := counter + 1;
end if;

A: I will try with counting the number of weekend days with a similar loop:
WHILE (v_copy > 0) LOOP
    end_date := end_date + 1;

    IF to_char(end_date, 'fmdy') IN ('sat', 'sun') THEN
         end_date := end_date + 1;
    ELSE
        v_copy := v_copy - 1;
    END IF;

  END LOOP;

And then after the looping process you can count the number of holidays in the table which are after the start_date and end_date and not in ('sat', 'sun').
SELECT COUNT(*) INTO v_custom_cnt
 FROM holiday_table
  WHERE to_char(holidays, 'fmdy') not in ('sat', 'sun') AND
     holidays BETWEEN start_date AND end_date;

Now add this number to your end_date and you will get the date of the nth business day. Of course before returning check if the new end_date is in ('sat', 'sun').
end_date := end_date + v_custom_cnt;

IF to_char(holidays, 'fmdy') in ('sat', 'sun') THEN
  end_date := next_day(end_date, 'monday');
END IF;

Finally the end_date is the date of the nth working day.
CREATE OR REPLACE FUNCTION add_n_working_days (
  start_date DATE,
  working_days PLS_INTEGER
) RETURN DATE AS

  end_date DATE := start_date;
  counter  PLS_INTEGER := 0;
  v_copy PLS_INTEGER := working_days;

  v_custom_cnt INTEGER := 0;
BEGIN

  IF working_days = 0 THEN
    end_date := start_date;
  ELSIF to_char(start_date, 'fmdy') IN ('sat', 'sun') THEN
    end_date := next_day(start_date, 'monday');
  END IF;

  WHILE (v_copy > 0) LOOP
    end_date := end_date + 1;

    IF to_char(end_date, 'fmdy') IN ('sat', 'sun') THEN
         end_date := end_date + 1;
    ELSE
        v_copy := v_copy - 1;
    END IF;

  END LOOP;

  SELECT COUNT(*) INTO  v_custom_cnt
    FROM holiday_table
  WHERE to_char(end_date, 'fmdy')  NOT IN ('sat', 'sun')
    AND holidays BETWEEN start_date AND end_date;

  end_date := end_date + v_custom_cnt;

  IF to_char(end_date, 'fmdy') IN ('sat', 'sun') THEN
    end_date := next_day(start_date, 'monday');
  END IF;

  RETURN end_date;

END add_n_working_days;

It is not 100% tested

A: Different approach: create a table that only lists business day and take nth value:
CREATE OR REPLACE FUNCTION add_n_working_days (
  start_date DATE, working_days PLS_INTEGER
) RETURN DATE AS
  l_end_date DATE := start_date;
  l_counter  pls_integer := 0;
BEGIN
  SELECT
    business_day
    INTO l_end_date
  FROM
  (
    WITH
    dates AS
      (SELECT start_date + level - 1  as dt FROM dual CONNECT BY level < 100)
    ,weekdates AS
    (SELECT dt as weekday FROM dates WHERE TO_CHAR(dt,'fmdy') NOT IN ('sat','sun'))
    ,business_days AS
    (
    SELECT weekday as business_day FROM weekdates
    MINUS
    SELECT holiday FROM so_holidays
    )
    SELECT business_day, ROW_NUMBER() OVER (ORDER BY 1) as rn from business_days
  )
  WHERE rn = working_days + 1;
  RETURN l_end_date;
END add_n_working_days;

A: SQL is set orientated so start thinking in terms of sets NOT iteration (no loops). Assuming you can designate a maximum number of days to be tested you can get what you want with a single simple query.
create or replace function add_n_working_days (
  start_date date, working_days pls_integer
) return date as
  working_date_ot date;
begin
    with date_list as (select trunc(start_date) + level - 1 tdate
                 from dual
                connect by level <= 5*working_days
               )
    select tdate
      into working_date_ot
      from ( select tdate, row_number() over(order by tdate) date_num
               from date_list
              where to_char(tdate,'fmdy') not in ('sat','sun')
                and not exists
                   (select null
                      from holiday_dates
                     where trunc(holiday_date) = tdate
                   )
            )
    where date_num = working_days;

    return working_date_ot;
end add_n_working_days;

How it works:
The function assumes the desired date exists within 5 times the number of days requested. So if 10 business hence are requested the resulting date will be within 50 days (that would be a whole lot of holidays if not).
The date_list CTE builds a list of potential dates out to the identified limit.
The sub select in the main filters the generated list eliminating Sat and Sun. It then probes the holiday table for the remaining dates and eliminating any any date in the table.
Remaining dates are numbered based on ascending value.
The main outer select then chooses the date number matching the working_days specified.
No Looping required. Just my .02 cents worth.


text:
Q: Doesn't show blob image I'm having problem with showing image which is stored in database as a blob. I searched in many forums, but couldn't find any answer.
I separated the code into two files. In index.php i insert image and try to load it from get_image.php file.
Here is index.php
<form action="index.php" method="POST" enctype="multipart/form-data">
                  File:
                  <input type="file" name="image"> <input type="submit" value="upload">
                </form>

                <?php
                  $file = $_FILES['image']['tmp_name'];

                  if(!isset($file)){
                    echo "Please select an image.";
                  }

                  else{
                    $image_name = mysql_real_escape_string($_FILES['image']['name']);
                    $image = mysql_real_escape_string(file_get_contents($_FILES['image']['tmp_name']));
                    $imageType = mysql_real_escape_string($_FILES['image']['type']);
                    $image_size = getimagesize($_FILES['image']['tmp_name']);

                    if($image_size == FALSE){
                      echo "That's not an image";
                    }
                    else{
                      if (!$insert = mysql_query("UPDATE 'table_name' SET `image` = '$image' WHERE 'row_name' = '$student_id'")){
                        echo "Problem updating image";
                      }

                      else{
                        echo "";
                      }

                    }
                  }
                ?>

And get_image.php
<?php

        $query = mysql_query("SELECT image FROM table_name WHERE student_id = 51686");
        while($row= mysql_fetch_assoc($query)){
            $imageData = $row['image'];
        }

        header("Content-type: image/png");
        echo $imageData;
?>

Can anyone help please. My php version is 5.2 At the output there is image icon, but no image. If I right click and try to save it as image, it's not an image format, it's saved as get_image.php. So I don't know what is the problem.

A: please try to insert record like this below
 $tmpImageName=$_FILES['files']['tmp_name'];
 $handle      = fopen( $tmpImageName, 'r' );
 $content = fread( $handle, filesize( $tmpImageName ) );
 fclose($handle);

 $sql='insert into imagetest(image)values("'.mysql_escape_string($content).'")';

 mysql_query($sql) or die(mysql_error());

and then try to display image like here
$res = mysql_query("SELECT * FROM imagetest");
 while ($row = mysql_fetch_assoc($res)) {
   echo "";
  }

A: $pdo = new PDO('mysql:dbname=database_name;host=localhost', 'username', 'password',
        array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));

      $imageName = mysql_real_escape_string($_FILES["image"]["name"]);
      $imageData = file_get_contents($_FILES["image"]["tmp_name"]);
      $imageType = mysql_real_escape_string($_FILES["image"]["type"]);

      $stmt = $pdo->prepare('INSERT INTO image (name,image) VALUES (:name,:image)');
      $stmt->bindParam(':image', $imageData, PDO::PARAM_LOB);
      $stmt->bindParam(':name', $imageName);
      $stmt->execute(array('name' => $imageName, 'image' => $imageData));
      echo "Image Uploaded";

      $res = mysql_query("SELECT * FROM image ");
      while ($row = mysql_fetch_assoc($res))
      {
        echo "";
      }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Button in the center of a card footer in Bootstraps I have this .card-footer:

    <button class="btn btn-theme pull-left" type="button" id="toleft"><</button>
    <button class="btn btn-theme" type="button" id="more">+</button>
    <button class="btn btn-theme pull-right" type="button" id="toright">></button>

The buttons .toleft and .toright are in the correct position, however the button #more should be exactly on the center of the footer, but it is still on the left.
Any ideas?

A: If you're seeing this in 2018 or beyond, please note that some of these old answers will not work with Bootstrap 4...
However, there is no need to include additional CSS as a couple of the previous answers suggest.
The pull-left and pull-right classes no longer work in Bootstrap 4.
Instead, we now use float-left and float-right to float our left and right buttons.
The easiest way to achieve the desired effect would be to start by centering the footer contents by adding the text-center class to the footer.
Next, we can float the left button with the float-left class and float the right button with the float-right class.
Here's the final HTML:

<button class="btn btn-theme float-left" type="button" id="toleft">left</button>
<button class="btn btn-theme" type="button" id="more">center</button>
<button class="btn btn-theme float-right" type="button" id="toright">right</button>

Which gives us the following result:

A: Bootstrap 3
You can use the following solution adding .text-center to the .card-footer container:

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

  <button class="btn btn-theme pull-left" type="button" id="toleft"><</button>
  <button class="btn btn-theme" type="button" id="more">+</button>
  <button class="btn btn-theme pull-right" type="button" id="toright">></button>

Bootstrap 4.0+
On Bootstrap 4.0+ there is no class .pull-left or .pull-right anymore. You have to use .float-left and .float-right instead. You can also use .text-center to center the second button.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

  <button class="btn btn-dark float-left" type="button" id="toleft"><</button>
  <button class="btn btn-dark" type="button" id="more">+</button>
  <button class="btn btn-dark float-right" type="button" id="toright">></button>

Note: I don't recommend to use custom CSS rules. Bootstrap is a CSS Framework to provide solutions for many design problems. Overwriting CSS properties on components can cause problems.

A: Just tried this with the latest alpha6 build of Bootstrap 4 (I'm assuming you're using BS4 as you mentioned the card component), and it looks as though the default behaviour is to align buttons in card footers to the middle anyway.
Note that I also had to introduce the .pull-left / .pull-right utility classes, as these no longer appear to be defined in the Bootstrap CSS.
See demo below:

.pull-left {
  float: left;
}

.pull-right {
  float: right;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

    Featured

Special title treatment

With supporting text below as a natural lead-in to additional content.

    Go somewhere

    <button class="btn btn-theme pull-left" type="button" id="toleft"><</button>
    <button class="btn btn-theme" type="button" id="more">+</button>
    <button class="btn btn-theme pull-right" type="button" id="toright">></button>

A: Try This :

.card-footer{
    text-align: center;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

     <button class="btn btn-theme pull-left" type="button" id="toleft"><</button>
     <button class="btn btn-theme" type="button" id="more">+</button>
     <button class="btn btn-theme pull-right" type="button" id="toright">></button>


text:
Q: Moons of the planets What is the phenomena behind gas giants like Jupiter and Saturn having a large number of moons as compared to other planets. Were the present state moons a part of their parent planet long time ago ?

A: You could look at the question from the other perspective i.e. why don't the inner planets have moons? The Earth only has a moon because it (probably) got hit by another planet while it was forming, and Mars' moons are probably captured asteroids.
Having said this, we don't know the answer to this question either. It's been suggested that the inner planets formed a lot closer to the Sun than they are now, and migrated outwards due to interactions with dust surrounding the Sun (the solar wind has since blown away this dust). It's possible that all the small bodies that hadn't aggregated into planets got ejected from the inner Solar System by interactions with the inner planets.
If you accept this argument then I guess the outer planets got moons because they were more widely spaced so the system was less chaotic. There's also a lot more junk floating about because the solar wind was too weak to blow away all the small particles.


text:
Q: Comportamento anômalo do Google Analytics Uso o Google Analytics em meu site porem ele tem um comportamento anômalo:

*

*Quando abro 2 até infinitas páginas do meu site em um unico navegador é
computado como um unico usuário ativo.

*Quando abro 2 até infinitas páginas do meu site em 2 navegadores são
computados como 2 usuários ativos.

*Quando fecho as páginas não é atualizado o numero de usuários ativos no site.

*Quando deixo as abas abertas porem sem qualquer atualização ou redirecionamento
o número de usuarios onlines é atualizado a 0.

Estou usando um código do google analytics assincrono e otimizado (O coloquei
em um arquivo .js externo (que contem outras funções javascript, porem não há
interfrencia entre variaveis)):
var _gaq = [['_setAccount', 'UA-63633330-1'], ['_trackPageview']];
(function(d, t){
    var g = d.createElement(t),
        s = d.getElementsByTagName(t)[0];
    g.src = 'http://www.google-analytics.com/ga.js';
    s.parentNode.insertBefore(g, s);
}(document, 'script'));

Qual a razão para este comportamento anômalo ou este é o comportamento adequado?
Link do site que disponibilizou a versão otimizada do Google Analytics: https://mathiasbynens.be/notes/async-analytics-snippet

A: Podemos dizer que sim, todos me parecem "corretos" com a lógica do funcionamento da maioria dos "contadores online", espero que isto lhe ajude:

Q: Quando abro 2 até infinitas páginas do meu site em um único navegador é computado como um único usuário ativo.

*

*R: Sim são considerados único, pois é necessários para fazer a métrica e geralmente usado para definir o passo-a-passo do cliente, por exemplo em um site de compras se o usuário abrir várias janelas ou abas será necessário verificar por onde ele passou até atingir o goal (neste exemplo seria concluir a compra)

Q: Quando abro 2 até infinitas páginas do meu site em 2 navegadores são computados como 2 usuários ativos.

*

*R: Cada navegador tem um User-Agent (identificação das tecnologias o qual o usuário está usando para navegar) diferente e também não usam a mesma sessão/cookies, portanto não é possível determinar que são usuário diferentes. Eles poderiam até usar o IP, mas se dois computadores usarem a mesma REDE o IP será igual e isto causaria conflitos e dados irreais (misturados).

Q: Quando fecho as páginas não é atualizado o numero de usuários ativos no site.

*

*R: O navegador tem um evento javascript chamado window.onbeforeunload, porém ele só funciona bem no front-end, se usa-lo para fazer uma requisição ajax por exemplo, ao momento que fechar o navegador ele vai chamar o ajax, mas não vai ter tempo de concluir a entrega do pedido no servidor, as vezes consegue, mas não é garantido. Eles poderiam usa-lo para auxiliar, mas ao invés disto eles utilizam um tempo aproximado de um minuto para verificar as atividades do usuário, se o usuário fechou o navegador, após um minuto ele é removido da "quantidade de usuários online" e este é o processo mais garantido de funcionar hoje em dia.

Q: Quando deixo as abas abertas porem sem qualquer atualização ou redirecionamento o número de usuários onlines é atualizado a 0.

*

*R: É a mesma situação do anterior, se o usuário está inativo no site mesmo que com abas abertas, o contador deve desconsiderar depois de um minuto (~aproximado) o usuário, pois o que importa é a atividade dentro do site, se o usário está em outra aba não tem porque contabilizar ele. No momento que ele executar uma atividade o contador atualiza.

Conclusão
Navegadores podem falhar, pode haver queda de energia, por isto o sistema de "um minuto" (~aproximado) é o melhor para verificar se o usuário está ativo se comparado ao evento window.onbeforeunload. Note que este "método" não é só no google, mas outros sistemas iguais e até mais simples usam o mesmo procedimento (como aqueles chats online de suporte ao visitante)


text:
Q: How to re-position popup with Scrolling containers Your reference element and popover could be located anywhere in the DOM. For example your reference element and popover element could be in different scrolling containers. Popover needs to handle any DOM context you throw at it.
Take the following HTML:

  Lots of text here
  <button id="reference">My Button</button>
  Lots of text here

My Centered Tooltip

When the scrolling container is scrolled, the reference element will change its location on the screen. However your tooltip is not "aware" of this happening, and so it won't track the reference element as it's scrolling.


text:
Q: New to Javascript (Discord bot), If-Else/Switch statements not working Premise:
I am far from a coding master, though not a complete novice, but am new to JavaScript and Discord. I've looked around and asked someone about this problem but to no avail, so any help would be much appreciated. (This is using Node.js, Discord.js)
I was starting to make a simple bot that would respond to your message, and I successfully did that. I then moved on to try to give it a switch statement to allow it to do different things based on what was said. Since I didn't know JavaScript I thought I'd start out simple and work my way up as I got familiar with it. However, this did not work so well.
Problem:
After setting up a switch statement I found that it would only use the first instance of the switch statement that was first initialized. It would never swap to the next one. In case switch statements don't work quite the same as I have seen before I changed it to an if/else statement. Strangely enough, the same results occurred. I simplified it down to its basic logic to no avail.
// Run dotenv
require('dotenv').config();

const fs = require('fs');
const Discord = require('discord.js');
const client = new Discord.Client();

//Set Var
var testNumb = 0;

// Code Start
  console.log("Initial value" + testNumb);
  if(testNumb == 0){
    console.log("Case 0: Entry value: " + testNumb);
    testNumb = 1;
    console.log("Case 0: Exit value: " + testNumb);
  }else if(testNumb == 1){
    console.log("Case 1: Entry value: " + testNumb);
    testNumb = 2;
    console.log("Case 1: Exit value: " + testNumb);
  }else if(testNumb == 2){
    console.log("Case 2: Entry value: " + testNumb);
    testNumb = 3;
    console.log("Case 2: Exit value: " + testNumb);
  }else if(testNumb == 3){
    console.log("Case 3: Entry value: " + testNumb);
    testNumb = 4;
    console.log("Case 3: Exit value: " + testNumb);
  }else{
    console.log("We made it!");
    console.log("Current Value: " + testNumb);
  };
console.log("Final value: " + testNumb);

Results in Console:
Initial value: 0
Case 0: Entry value: 0
Case 0: Exit value: 1
Final value: 1

Tried:
Thinking the problem might be related to an infinite loop scenario I encapsulated the entire if/else in a
var testLoopGuard = 0;
if(testLoopGuard == 0){
  if(testNumb == 4){ testLoopGuard = 1; };
  console.log(testLoopGuard);
};

Which makes no difference, but testLoopGuard stays at 0.
Results in Console:
Initial value: 0
Case 0: Entry value: 0
Case 0: Exit value: 1
0
Final value: 1

Tried:
My next thought was that perhaps the initial set var testNumb = 0 was being looped instead of just initialized. So I changed it to var testNumb; to call the initialization which sets it to null and initialized it in Case 0 by changing the logic to look for an undefined value. The results stayed the same.
Tried:
Next I considered that perhaps it wasn't looping as the main Loop would normally do, so it was only running the first condition and then the program essentially ended. This didn't seem the likely case though, since it was able to listen for user input seemingly infinity when using something such as:
client.on('message', msg => {
  if (msg.content === 'ping') {
    msg.reply('pong');
  }
});

Tried:
Out of my own curiosity I tried encapsulating the entire block with a client.on('message'... setup, adding the login as bot code to use it. This semi-worked, but would only go up one step per user entry, but having to enter text to allow it to go up a step or register a change is far from ideal in any program.
client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
});

client.login(process.env.DISCORD_TOKEN);

client.once('ready', () => {
    console.log('Ready!');
});

client.on('message', message => {
*original code*
});

Tried:
After that I tried moving the console.log("Initial value: " + testNumb); and the console.log("Final value: " + testNumb); outside of the encapsulation, but they only worked once on the first run and never again.
Results in Console:
Initial value: 0
Final value: 0
Case 0: Entry Value: 0
Case 0: Exit Value: 1
*user entry*
Case 1: Entry Value: 1
Case 1: Exit Value 2
*user entry*
Case 2: Entry Value: 2
Case 2: Exit Value 3

and so on.
Thoughts:
With all this in mind, there is clearly a loop going on to check contents but it for some reason isn't actually doing anything with the contents after the first run through the loop. I am likely missing something simple and I can't find any information on loops other than while and for loops, so I can only assume the main loop is built in by default since it does have the ability to listen and repeat, but if so why is this simple sequence not working? I know it isn't the most fancy way to do things and there are likely much better ways to actually make a full program/bot, but understanding why this doesn't work and how to fix it is pretty key. Thank you for your time and help in advance!

A: Look like the if/else statement is running as expected.
I mean, you init a variable testNumb to 0 and test it, it end up in the first case, that's pretty normal here because the first case compare the variable to 0. How can this be different?
I bet if you init the testNumb variable to 1, it will end up in the second case.

A: Oh, I see what you did.. look:
console.log("Initial value" + testNumb);
if(testNumb == 0){
  console.log("Case 0: Entry value: " + testNumb);
  testNumb = 1;
  console.log("Case 0: Exit value: " + testNumb);
}

There are two problems. The first is with testNumb = 1;
You can not change a value outside of the if-statements scope. What happens is testNumb will be redefined to 1 until you close the body with an }
The second problem would be that an if - else statement stops reading the rest of your code if something evaluates to true.
Now how can you make testNumb increment in your case? With a for loop. It would look something like this:
// in this example I use "i" instead of "testNumb"
for (let i = 0; i < 5; i++) {
  console.log("Case " + i + ": Entry value: " + i);
  console.log("Case " + i + ": Exit value: " + i++);
};
console.log("We made it!");

A: I found the solution to the problem after a lot of trial and error.
Within Javascript and Node.js/Discord.js everything is complied and ran once and will only be referenced if another action is called upon, such as a message. The code does end up working as it should if it is called by something like a timer set to run over the code again. It does store the value, but will never touch it again unless an eventlistener calls upon it to work again. Loops wont work, as far as I can find, and will stall since it never finishes compiling. There is no way to use a "main loop" setup. So the only way to do that is to create a psudo loop with a reoccurring eventlistener like timeout.

I'm not sure if the explanation is the greatest or I missed anything, but if there are any better explanations I am more than happy to look them over, until then I'll mark this question as answered. Thanks for the input everyone!


text:
Q: WinHttp responds with ERROR_WINHTTP_INVALID_SERVER_RESPONSE on WinXP despite receiving 200/OK response I am trying to debug an issue, but could use some pointers from others suffering similar fate.  The issue seems to be with Windows XP SP3 and use of the WinHttp library with certificates installed.  Under these conditions, WinHttp throws a WindowsError (ERROR_WINHTTP_INVALID_SERVER_RESPONSE), even though Wireshark shows it received the 200/OK response along with the XML data that was expected.  The WinHttp library is obviously doing some additional error checking that is causing it to think something is not right with the response.  Running the same code on a Windows 7 machine, produces exactly the same request and responses in Wireshark, except that WinHttp doesn't invalidate the response with the ERROR_WINHTTP_INVALID_SERVER_RESPONSE error; it seems to think everything is okay.
I have done some Googling and spent more time than I would like changing options.  My next port of call is to setup an SSH tunnel running netcat, so that I can identify if any of the headers are causing the problem.  Process of elimination.
Unless of course, somebody already knows the answer?
Versions
Python 2.7.3
WinHttp 5.1 (the usual one you get with Windows XP Sp3 IE 8)
Windows XP Professional SP3 (Automatic updates seem up-to-date)
Note
This also happens on Windows Server 2003
Update
I can reproduce this issue using a simple script to fake a connection request to the server.
Script
(function() {

var soapXmlReq =
    '<SOAP-ENV:Envelope xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ZSI="http://www.zolera.com/schemas/ZSI/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><SOAP-ENV:Header></SOAP-ENV:Header><SOAP-ENV:Body xmlns:ns1="urn:vim25"><ns1:RetrieveServiceContent><ns1:_this type="ServiceInstance">ServiceInstance</ns1:_this></ns1:RetrieveServiceContent></SOAP-ENV:Body></SOAP-ENV:Envelope>',

    soapXmlReqHeaders = {
        'Content-Type': 'text/xml; charset="utf-8"',
        'SOAPAction': 'urn:vim25/5.1',
        'User-Agent': 'VMware VI Client/5.0.0',
        'Content-Length': soapXmlReq.length,
        'Accept': '*/*',
        'Host': 'vcenter',
        'Connection': 'Keep-Alive'
    };

function fakeLogin() {
    WScript.StdOut.WriteLine("ActiveXObject('WinHttp.WinHttpRequest.5.1')");

    var req = WScript.CreateObject("WinHttp.WinHttpRequest.5.1"),
        result, header;

    WScript.StdOut.WriteLine("Open('POST', 'https://vcenter/sdk', false)");
    req.Open("POST", "https://vcenter/sdk", false);

    for (header in soapXmlReqHeaders) {
        WScript.StdOut.WriteLine("SetRequestHeader('" + header + ": " + soapXmlReqHeaders[header] + "')");
        req.SetRequestHeader(header, soapXmlReqHeaders[header]);
    }

    //WScript.StdOut.WriteLine("Send('" + soapXmlReq + "')");
    WScript.StdOut.WriteLine("Send()");
    req.Send(soapXmlReq);

    WScript.StdOut.WriteLine("ResponseText = " + req.ResponseText);
}

fakeLogin();

})();

Just run the script using CScript.exe and the output comes out on stdout.
I have noticed that the response packets are larger than the MTU, so they get fragmented.  Would this have anything to do with it?


text:
Q: Convert data received from a socket.recv (bytes) to a boolean value in ironpython I am using a python script as a TCP client.  At one point it receives what should be a bool back from the server.  When I was first writing this and testing it on a machine that was using a regular python install I was able to use the following code from the struct module to unpack the data received back as a bool
data = socket.recv(BUFFER_SIZE)
result = struct.unpack("?", data)[0]
if not result:
    #do stuff here

I currently need to perform the same task in an environment that only uses ironpython.  When I attempt to run the code I get the following:
ImportError: No module named struct

After a bit of digging it seems that the struct module in regular python doesn't exist in ironpython (I believe a struct module exists, but it is for interfacing with c/c++ structs)
How can I take the data from a TCP socket.recv and convert it from the bytes format actually received to the bool type I need it to be in ironpython?

A: After some more digging I came across this post which was asking about converting a string of bytes to an int.
I found the solution offered in this answer avoided having to import any modules and worked quite well, I needed to perform an additional conversion to bool so my final result looks like this:
data = sock.recv(BUFFER_SIZE)
result = bool(int(data.encode('hex'), 16))


text:
Q: I get incompatible types in the assignment? int k[4] = {1,2,3,4};
int kk[4];
kk=k;

I get incompatible types in the assignment??
Do I have to loop and assign each value in the array, or is there an easier way?
Thank you

A: You have to loop, or use a library call.
One option would be memcpy(kk, k, sizeof(k));. For this you must #include <string.h>.

A: Yes. Arrays don't behave like primitive data types in C. You have to loop over the array and assign each value. You can't just assign one array to another (especially since kk is really an int pointer). Not too hard though:
int i;
for (i = 0; i < 4; i++)
    kk[i] = k[i];

A: There is no copy assignment of good old C arrays. So yes, you have to loop through and copy each element.


text:
Q: Is there shortcut when choose elements of struct? I'm trying to sort a array of struct. But i want sort by one the elements. For example I'm sorting with bubble sort.
struct example{
    int num;
    char str[5];
} ex[90];

for(int i = 0; i < 88; i++){
    for(int o = 0; o < 88; o++){
        if(ex[o].num > ex[o + 1].num){
            swap(ex[o].num, ex[o + 1].num);
        }
    }
}

In this code how can i change ex[o].num as ex[o].str without writing code again?

A: One could implement comparison functions and use the standard library's qsort. It's hard to beat the standard library for general sorting except if you want a stable sort. qsort takes in a compar,

The compar argument is a pointer to the comparison function, which is called with two arguments that point to the elements being compared. The application shall ensure that the function returns an integer less than, equal to, or greater than 0, if the first argument is considered respectively less than, equal to, or greater than the second.

Like such,
#include <stdlib.h> /* EXIT_* qsort */
#include <stdio.h>  /* printf */
#include <string.h> /* strcmp */
#include <assert.h>

struct Example {
    int num;
    char str[5];
} ex[90];

static const size_t ex_size = sizeof ex / sizeof *ex;

static void fill(struct Example *const example) {
    assert(example);
    example->num = rand() / (RAND_MAX / 100.0);
    example->str[0] = rand() / (RAND_MAX / 26.0) + 'A';
    example->str[1] = rand() / (RAND_MAX / 26.0) + 'a';
    example->str[2] = rand() / (RAND_MAX / 26.0) + 'a';
    example->str[3] = rand() / (RAND_MAX / 26.0) + 'a';
    example->str[4] = '\0';
}

static void print(const struct Example *const example) {
    assert(example);
    printf("%d\t\"%s\"\n", example->num, example->str);
}

/* Implements <Example>Comparator. */
static int comp_num(const void *va, const void *vb) {
    const struct Example *a = va, *b = vb;
    return (a->num > b->num) - (a->num < b->num);
}

/* Implements <Example>Comparator. */
static int comp_str(const void *va, const void *vb) {
    const struct Example *a = va, *b = vb;
    return strcmp(a->str, b->str);
}

int main(void) {
    size_t i;
    for(i = 0; i < ex_size; i++) fill(&ex[i]);
    for(i = 0; i < ex_size; i++) print(&ex[i]);
    printf("Sorting by num.\n");
    qsort(ex, ex_size, sizeof *ex, &comp_num);
    for(i = 0; i < ex_size; i++) print(&ex[i]);
    printf("Sorting by str.\n");
    qsort(ex, ex_size, sizeof *ex, &comp_str);
    for(i = 0; i < ex_size; i++) print(&ex[i]);
    return EXIT_SUCCESS;
}


text:
Q: Scrolling header with two list views I have a header section that I would like to scroll with a list view below. The problem is that I have a toggle below the header section that allows the user to switch between two list views. What would be the best way to have a header section scroll in sync with the two list views below?

A: I can share a short overview to help you:
<ScrollView ..>
     <LinearLayout>
           <HeaderView></HeaderView>
           <ToggleButton></ToggleButton>
           <ListView></ListView>
           <ListView></ListView>
     </LinearLayout>
</ScrollView>

The tricky thing is: You have to flip the visibility of the two listView by visible and gone in the toggle button.
1st click on toggle will make it
listView1.setVisibility(View.GONE)
listView2.setVisibility(View.Visible)

2nd click on toggle will make it
listView2.setVisibility(View.GONE)
listView1.setVisibility(View.Visible)


text:
Q: Short syntax for NSString Multilanguage allocation I've a method called S that convert an NSString* through a KeyValue approach to another NSString* in another language
static inline NSString* S(NSString *stringa);

For a trivial migration to Java code I've defined this preprocessor macro:
   #define String NSString*
   #define SS(stringa) S(@#stringa)

So in my objc code I can do something like this:
String translated = SS(string_to_translate);

but string_to_translate  is a NSString* so I can't use brace tu include the real string. My intention, for an easy migration to Java syntax was to have a macro in objc that can do this:
String translated = SS("string_to_translate");

without using objc "@" but only brace parentheses.


text:
Q: Exit for loop without using a break statement public static void enterInts()
{
    int i = 0;
    int[] userArray = new int[9];

    System.out.println("Enter up to 10 integers, type 0 when done");

    for(i = 0; i < userArray.length; i++)
    {
        if (keyboard.nextInt() != 0)
            userArray[i] = keyboard.nextInt();
        else
            break;
    }//for
    posOrNeg(userArray);
}//enterInts

My professor REALLY hates break statements and continue() in loops, so I would like to know if there is anyway to exit this for loop once "0" is typed without using one.

A: One way is to call nextInt() in the loop condition:
for (int i = 0; i < userArray.length && (userArray[i] = keyboard.nextInt()) != 0; i++);

A: The break; and continue; are the best way to control the flow of a loop. Anyway, It's a reality that professors around the world are haters of that.
With this kind of nonsense limitation, you have to be creative if you want to end up with a code that doesn't look like shit.
My suggestion, is a little bit obfuscated and makes to code harder to understand, but is the closest thing to "break":
int length = 10;
for(i = 0; i < length; i++)
{
    i = length; // This produces the same effect as break.
}

Good luck with that, stay cool and keep things nice and clean!

A: First, as someone else said, you should read nextInt() into a variable so you can assign it later. Your code will ask for a number, and then if that number is not zero, it will forget what the number was and then ask for another number to be input, which will get assigned.
As for potential solutions: One idea would be to move the loop to its own method, and then you could just use "return" in lieu of "break". It's effectively the same concept, but avoids the break keyword. I worry that he may not like that either though. It's not clear why he doesn't like break, so it's hard to say.
Another solution would be to replace the for loop with a while loop, get the next input at the end of the loop, and then have the conditional for the loop include the number not being zero.

A: just replace break; with return;


text:
Q: is it possible to set timout in Axios get request? In a small VueJS app, I'm using Axios to handle HTTP requests!
I have a simple GET request and I want to add a timeout parameter to my request, but it's not working...
are we allowed to use a timeout in GET request or am I doing something wrong?
this is my code:
...
Vue.prototype.$http = Axios
...
this.$http.get(stringUrl, {parameters: {limit: 5000}},timeout: 30000).then(data => {...})

GET works fine but, but it's instant. I want the GET request to wait for 30000 then get data, but it's not the case.

A: Axios timeout is responsible for response timeout. If you want to wait for the data for about 30 seconds, you can use a Promise to wait for about 30 seconds.
async function getData() {
   const data = await this.$http.get(stringUrl, {parameters: {limit: 5000}},timeout: 30000)
   return new Promise(res =>  setTimeout(res, 30000))
}


text:
Q: ManyToMany field query returns empty set but not empty I have a many-to-many field that when queried is returning an empty QuerySet but is definitely not empty. I can see this from the admin page.
I can see in admin that there is an Application object in Vacancy(id=1).
Plus when I query the job for an Application, it returns Vacancy(id=1).
I have included my shell script below.
models.py
class Vacancy(models.Model):
    CATEGORY_CHOICES = [
        ('ADMINISTRATION', 'Administration'),
        ('CONSULTING', 'Consulting'),
        ('ENGINEERING', 'Engineering'),
        ('FINANCE', 'Finance'),
        ('RETAIL', 'Retail'),
        ('SALES', 'Sales'),
    ]
    employer = models.ForeignKey('Employer', on_delete=models.CASCADE)
    job_title = models.CharField(max_length=35, default=None)
    main_duties = models.TextField(default=None, validators=[
        MinLengthValidator(650),
        MaxLengthValidator(2000)
    ])
    person_spec = models.TextField(default=None, validators=[
        MinLengthValidator(650),
        MaxLengthValidator(2000)
    ])
    salary = models.PositiveIntegerField(default=None, validators=[
        MinValueValidator(20000),
        MaxValueValidator(99000)
    ])
    city = models.CharField(choices=CITY_CHOICES, max_length=11, default=None)
    category = models.CharField(choices=CATEGORY_CHOICES, max_length=15, default=None)
    max_applications = models.PositiveSmallIntegerField(blank=True, null=True)
    deadline = models.DateField(blank=True, null=True)
    applications = models.ManyToManyField('Application', blank=True)
    active = models.BooleanField(default=True)

    class Meta:
        verbose_name_plural = 'vacancies'

class Application(models.Model):
    STAGES = [
        ('pre-selection', 'PRE-SELECTION'),
        ('shortlisted', 'SHORTLISTED'),
        ('rejected pre-interview', 'REJECTED PRE-INTERVIEW'),
        ('rejected post-interview', 'REJECTED POST-INTERVIEW'),
        ('successful', 'SUCCESSFUL')
    ]
    candidate = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    job = models.ForeignKey('Vacancy', on_delete=models.CASCADE)
    cv = models.CharField(max_length=35, default=None)
    cover_letter = models.TextField(default=None, validators=[
        MinLengthValidator(0),
        MaxLengthValidator(2000)
    ])
    submitted = models.DateTimeField(auto_now_add=True)
    stage = models.CharField(choices=STAGES, max_length=25, default='pre-selection')

manage.py shell
>>> from recruit.models import *
>>> RA = Vacancy.objects.get(id=1)
>>> RA
<Vacancy: 1 Research Administrator>
>>> RA.applications.all()
<QuerySet []>
>>> App = Application.objects.get(id=1)
>>> App.job.id
1
>>> App.job
<Vacancy: 1 Research Administrator>
>>>

Any ideas on why this isn't working?

A: Solved:
class Vacancy(models.Model):
    applications = models.ManyToManyField('Application', symmetrical=False, blank=True)

Was missing the symmetrical=False attribute on the applications field!


text:
Q: TC-885 trying to re-install WIN 11 from UBS for the fifth attempt I have completely restarted my NVe ssd with DISKPART clean, convert gpt, and run the WIN 11 Install option as a New Computer setup. The installation runs through to completion, I then run the Windows Updates, which it runs through to the 2nd last Cumulative Update and then on restart goes to a black screen and that's it, so far this is the 5th attempt.
What should I try next,
Vince


text:
Q: How to detect squares in video with OpenCV? So I combined squares.cpp with cvBoundingRect.cpp code to detect squares in video. I therefore, had to convert from IplImage to Mat type so that findSquares and drawSquares methods could run (By using cvarrToMat function). But unfortunately, after successful compilation I get this error when running:

OpenCV Error: Assertion failed (j < nsrcs && src[j].depth() == depth) in mixChannels, file /Users/Desktop/opencv-3.0.0-rc1/modules/core/src/convert.cpp, line 1205
  libc++abi.dylib: terminating with uncaught exception of type cv::Exception: /Users/Desktop/opencv-3.0.0-rc1/modules/core/src/convert.cpp:1205: error: (-215) j < nsrcs && src[j].depth() == depth in function mixChannels
  Abort trap: 6

Here's the code:
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui/highgui.hpp"

#include <iostream>
#include <math.h>
#include <string.h>

using namespace cv;
using namespace std;

int thresh = 50, N = 11;
const char* wndname = "Square Detection Demo";

// finds a cosine of angle between vectors
// from pt0->pt1 and from pt0->pt2
static double angle( Point pt1, Point pt2, Point pt0 )
{
double dx1 = pt1.x - pt0.x;
double dy1 = pt1.y - pt0.y;
double dx2 = pt2.x - pt0.x;
double dy2 = pt2.y - pt0.y;
return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
}

// returns sequence of squares detected on the image.
// the sequence is stored in the specified memory storage
static void findSquares( const Mat& image, vector<vector<Point> >& squares )
{
squares.clear();

Mat pyr, timg, gray0(image.size(), CV_8U), gray;

// down-scale and upscale the image to filter out the noise
pyrDown(image, pyr, Size(image.cols/2, image.rows/2));
pyrUp(pyr, timg, image.size());
vector<vector<Point> > contours;

// find squares in every color plane of the image
for( int c = 0; c < 3; c++ )
{
    int ch[] = {c, 0};
    mixChannels(&timg, 1, &gray0, 1, ch, 1);

    // try several threshold levels
    for( int l = 0; l < N; l++ )
    {
        // hack: use Canny instead of zero threshold level.
        // Canny helps to catch squares with gradient shading
        if( l == 0 )
        {
            // apply Canny. Take the upper threshold from slider
            // and set the lower to 0 (which forces edges merging)
            Canny(gray0, gray, 0, thresh, 5);
            // dilate canny output to remove potential
            // holes between edge segments
            dilate(gray, gray, Mat(), Point(-1,-1));
        }
        else
        {
            // apply threshold if l!=0:
            //     tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
            gray = gray0 >= (l+1)*255/N;
        }

        // find contours and store them all as a list
        findContours(gray, contours, RETR_LIST, CHAIN_APPROX_SIMPLE);

        vector<Point> approx;

        // test each contour
        for( size_t i = 0; i < contours.size(); i++ )
        {
            // approximate contour with accuracy proportional
            // to the contour perimeter
            approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);

            // square contours should have 4 vertices after approximation
            // relatively large area (to filter out noisy contours)
            // and be convex.
            // Note: absolute value of an area is used because
            // area may be positive or negative - in accordance with the
            // contour orientation
            if( approx.size() == 4 &&
                fabs(contourArea(Mat(approx))) > 1000 &&
                isContourConvex(Mat(approx)) )
            {
                double maxCosine = 0;

                for( int j = 2; j < 5; j++ )
                {
                    // find the maximum cosine of the angle between joint edges
                    double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
                    maxCosine = MAX(maxCosine, cosine);
                }

                // if cosines of all angles are small
                // (all angles are ~90 degree) then write quandrange
                // vertices to resultant sequence
                if( maxCosine < 0.3 )
                    squares.push_back(approx);
            }
        }
    }
}
}

// the function draws all the squares in the image
static void drawSquares( Mat& image, const vector<vector<Point> >& squares )
{
for( size_t i = 0; i < squares.size(); i++ )
{
    const Point* p = &squares[i][0];
    int n = (int)squares[i].size();
    polylines(image, &p, &n, 1, true, Scalar(255,0,0), 3, LINE_AA);
}

imshow(wndname, image);
}

CvRect rect;
CvSeq* contours = 0;
CvMemStorage* storage = NULL;
CvCapture *cam;
IplImage *currentFrame, *currentFrame_grey, *differenceImg, *oldFrame_grey;

bool first = true;

int main(int argc, char* argv[])
{
//Create a new movie capture object.
   cam = cvCaptureFromCAM(0);

   //create storage for contours
   storage = cvCreateMemStorage(0);

   //capture current frame from webcam
   currentFrame = cvQueryFrame(cam);

   //Size of the image.
   CvSize imgSize;
   imgSize.width = currentFrame->width;
   imgSize.height = currentFrame->height;

   //Images to use in the program.
   currentFrame_grey = cvCreateImage( imgSize, IPL_DEPTH_8U, 1);

namedWindow( wndname, 1 );
    vector<vector<Point> > squares;

while(1)
   {
          currentFrame = cvQueryFrame( cam );
          if( !currentFrame ) break;

          //Convert the image to grayscale.
          cvCvtColor(currentFrame,currentFrame_grey,CV_RGB2GRAY);

          if(first) //Capturing Background for the first time
          {
                 differenceImg = cvCloneImage(currentFrame_grey);
                 oldFrame_grey = cvCloneImage(currentFrame_grey);
                 cvConvertScale(currentFrame_grey, oldFrame_grey, 1.0, 0.0);
                 first = false;
                 continue;
          }

          //Minus the current frame from the moving average.
          cvAbsDiff(oldFrame_grey,currentFrame_grey,differenceImg);

          //bluring the differnece image
          cvSmooth(differenceImg, differenceImg, CV_BLUR);

          //apply threshold to discard small unwanted movements
          cvThreshold(differenceImg, differenceImg, 25, 255, CV_THRESH_BINARY);

          //find contours

cv::Mat diffImg = cv::cvarrToMat(differenceImg);
cv::Mat currFrame = cv::cvarrToMat(currentFrame);

          findSquares(diffImg, squares);

          //draw bounding box around each contour
          drawSquares(currFrame, squares);

          //display colour image with bounding box
          cvShowImage("Output Image", currentFrame);

          //display threshold image
          cvShowImage("Difference image", differenceImg);

          //New Background
          cvConvertScale(currentFrame_grey, oldFrame_grey, 1.0, 0.0);

          //clear memory and contours
          cvClearMemStorage( storage );
          contours = 0;

          //press Esc to exit
          char c = cvWaitKey(33);
          if( c == 27 ) break;

   }

// Destroy the image & movies objects
   cvReleaseImage(&oldFrame_grey);
   cvReleaseImage(&differenceImg);
   cvReleaseImage(&currentFrame);
   cvReleaseImage(&currentFrame_grey);

return 0;
}

A: As the error message says, your problem is in cv::mixChannels(). See documentation.
Or you could simply do something like
cv::Mat channels[3];
cv::split(multiChannelImage, channels);

and then access each channel using
cv::Mat currChannel = channels[channelNumber]


text:
Q: MySQL Indexes in Doctrine / Zend Framework 2 I have some serious Performance Problems and i found out that it is because the lack of Indexes in MySQL. So i added an Index to the Table Definition of the Entity:
@ORM\Table(
    name="test",
    indexes={
        @ORM\Index(name="test_idx", columns={"testfield"})
    }
)

These lines are ok (hopefully) but resulting in simply nothing, When i run doctrine orm:validate-schema it says, that the Database is in Sync. When i add the Index manually to MySQL it says it is no longer in sync, and wants to drop the index. I am a little bit confused because the CLI-Tool does not add the Index (but drops it, if it exists), and i am not getting any error message? What ist wrong?

A: Should work this way, though, the Index-Support ist broken at the moment. Have a look at:
https://github.com/doctrine/DoctrineORMModule/issues/368


text:
Q: Custom Segue with UIViewAnimationOptionTransitionCurlDown I'd like create a custom segue to swap ViewControllers with a curl up animation but I can't find a way, What would be the -(void)perform for this?
I've got this
-(void)perform{
    UIViewController *dst = [self destinationViewController];
    UIViewController *src = [self sourceViewController];
    [UIView beginAnimations:nil context:nil];
    //change to set the time
    [UIView setAnimationDuration:1];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:src.view    cache:YES];
    [UIView commitAnimations];
}

But I don't get to change the view, anyway thanks for your help!

A: Nevermind, I solved it, for the record the only thing I had to do was add a Navigation Controller and then I could use custom segues like:
- (void) perform {
    UIViewController *src = (UIViewController *) self.sourceViewController;
    UIViewController *dst = (UIViewController *) self.destinationViewController;
    [UIView transitionWithView:src.navigationController.view duration:0.3
                       options:UIViewAnimationOptionTransitionFlipFromBottom
                    animations:^{
                        [src.navigationController pushViewController:dst animated:NO];
                    }
                    completion:NULL];
}


text:
Q: Script task output to check if condition From the script task I get an output
{
"resultSetCount": 1,
"recordsAffected": 0,
"resultSets": [
{
"rowCount": 1,
"rows": [
{
"flag": 1
}
]
}
],
how to build an expression to check if the flag is 1
@equals(activity('Script1').output.resultSets.flag,1)
This is not working

A: Use this expression to get the required output value from script activity output in If Condition.
@equals(activity('Script1').output.resultSets[0]['rows'][0].flag,1)


text:
Q: discord.py Passing context and self to function in class I am trying to create a bot, which uses discord.py's VoiceClient.
The problem is, when you name a variable in a function it doesn't get passed on to the other functions. So the variable voicebot doesn't get passed on to the other functions (which are for making the bot leave or talk)
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=commands.when_mentioned_or("~"),intents=intents, owner_id=587573816360960022)

...Other functions...

@bot.command(name='join', help='Joins the voice channel you are in')
async def JoinVoiceofAuthor(ctx):
   vchannel = ctx.message.author.voice
   if vchannel != None:
       if "voicebot" not in globals():
           global voicebot
           voicebot = await vchannel.channel.connect()
       else:
           if voicebot.is_connected():
                   return
           if vchannel != None:
               voicebot = await vchannel.channel.connect()
       await ctx.send('Joining you, '+str(ctx.message.author.mention)+', in voice channel "'+str(vchannel.channel)+'"')
   else:
       await ctx.send('Sorry,'+str(ctx.message.author.mention)+', you are not in a voice channel')

...Other functions...

I tried making voicebot a global variable, but found out, that you can't change global varibales from a function.
So my next idea was to make the bot a class:
class TheBot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.all()

        super().__init__(intents=intents, command_prefix='~',  owner_id=587573816360960022)
        members = inspect.getmembers(self)
        for name, member in members:
            if isinstance(member, commands.Command):
                if member.parent is None:
                    self.add_command(member)

...Other functions...

    @commands.command(name='join', help='Joins the voice channel you are in')
    async def JoinVoiceofAuthor(self, ctx):
        vchannel = ctx.message.author.voice
        if vchannel != None:
            if "voicebot" not in globals():
                self.voicebot = await vchannel.channel.connect()
            else:
                if self.voicebot.is_connected():
                        return
                if vchannel != None:
                    self.voicebot = await vchannel.channel.connect()
            await ctx.send('Joining you, '+str(ctx.message.author.mention)+', in voice channel "'+str(vchannel.channel)+'"')
        else:
            await ctx.send('Sorry,'+str(ctx.message.author.mention)+', you are not in a voice channel')

...Other functions...

But that also didn't work, because the Context was also passed on to self and not to ctx
Does someone have a solution for this?

A: If you want to change a global variable from a function, you must use the global keyword from inside the function:
x = 50
def add_to_x(num):
    global x
    x += num

print(x)
add_to_x(10)
print(x)

#The Output is this:
50
60

And an implementation in discord.py would be:
x = 50
@bot.command()
async def add_to_x(ctx,amount):
    global x
    print(x)
    x += int(amount)
    print(x)

A: As Parasol Kirby said, you need to use the global keyword. To adapt this to your case we need to make some changes.
To make the voicebot variable global just add global voicebot at the top of the command. That way you can use this variable from every function.
Then to check if the bot is already connected to a voice channel, we do not need to use the voicebot variable. You can create a function that returns True if the bot is in a voice channel like this:
def is_connected(ctx):
    voice_client = discord.utils.get(ctx.bot.voice_clients, guild=ctx.guild)
    return voice_client and voice_client.is_connected()

Now to check if the bot is not connected to a voice channel from within the command, just use the is_connected function and "pass in" the context.
if not is_connected(ctx):

So the full code looks like this:
def is_connected(ctx):
    voice_client = discord.utils.get(ctx.bot.voice_clients, guild=ctx.guild)
    return voice_client and voice_client.is_connected()

@bot.command(name='join', help='Joins the voice channel you are in')
async def JoinVoiceofAuthor(ctx):
    global voicebot

    vchannel = ctx.message.author.voice
    if vchannel != None:
        if not is_connected(ctx):
            voicebot = await vchannel.channel.connect()
            await ctx.send('Joining you, '+str(ctx.message.author.mention)+', in voice channel "'+str(vchannel.channel)+'"')


text:
Q: Adding wp_ajax to a theme outside functions.php (on specific template page) I'm doing a function which requires the use of the wp_ajax action.
I've followed this guide to set it up with the differences of adding the requesting the object AJAX file in functions.php and also added
if(isset($_REQUEST['action'])) {
    do_action('wp_ajax_'.$_REQUEST['action']);
    do_action('wp_ajax_nopriv_'.$_REQUEST['action']);
}

to make it work.
Issue is that obviously having the file in functions.php causes every page to initialise workflow, but I only want it on one particular template file.
I could add it as a plugin I'm aware, but certain functions used are global to the theme and will never be used on any other theme so doesn't make sense in my mind to do that.
Ideally, I would just like to do require('ajax_file.php'); in the template file, but that's the main issue here is I don't think I can (unless somebody can correct me). So if there is an easy way to call it from the functions.php file without every other page also calling it then that would be a massive help.
Thanks!

A: Just drop it in a plugin. Theme = view. Plugin = constructor. I keep most of my stuff in plugins. IMHO only stuff that belongs to the visual part should be in the Theme. And yes, you can do a simple require( plugin_dir_path( $file_name ) ); for subfiles.


text:
Q: Pidgin-Latex has an "Error while reading the generated image!" I had no errors installing pidgin-latex via apt-get and pidgin runs fine before and after. The plugin is activated. The only problem I have is that (almost) every time a Latex message should be shown, instead the following message pops up and the text is not converted. For example, after sending the message $$test$$ this error message popped up:

Error while reading the generated image!
Datei »/tmp/purpleA0SRPY.png« konnte nicht geöffnet werden: Datei oder Verzeichnis nicht gefunden

The second paragraph is German and means something like

File /tmp/purpleA0SRPY.png could not be opened: File or directory not found

This is what my command line I started pidgin with said about it:
This is dvipng 1.15 Copyright 2002-2015 Jan-Ake Larsson
This is pdfTeX, Version 3.14159265-2.6-1.40.16 (TeX Live 2015/Debian) (preloaded format=latex)
restricted \write18 enabled.
entering extended mode
(/tmp/purpleOZIFPY.tex
LaTeX2e <2016/02/01>
Babel <3.9q> and hyphenation patterns for 3 language(s) loaded.
(/usr/share/texlive/texmf-dist/tex/latex/base/article.cls
Document Class: article 2014/09/29 v1.4h Standard LaTeX document class
(/usr/share/texlive/texmf-dist/tex/latex/base/size12.clo))
(/usr/share/texlive/texmf-dist/tex/latex/graphics/color.sty
(/usr/share/texlive/texmf-dist/tex/latex/latexconfig/color.cfg)
(/usr/share/texlive/texmf-dist/tex/latex/graphics/dvips.def)
(/usr/share/texlive/texmf-dist/tex/latex/graphics/dvipsnam.def))
(/usr/share/texlive/texmf-dist/tex/latex/graphics/graphicx.sty
(/usr/share/texlive/texmf-dist/tex/latex/graphics/keyval.sty)
(/usr/share/texlive/texmf-dist/tex/latex/graphics/graphics.sty
(/usr/share/texlive/texmf-dist/tex/latex/graphics/trig.sty)
(/usr/share/texlive/texmf-dist/tex/latex/latexconfig/graphics.cfg)))
(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsmath.sty
For additional information on amsmath, use the `?' option.
(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amstext.sty
(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsgen.sty))
(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsbsy.sty)
(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsopn.sty))
(/usr/share/texlive/texmf-dist/tex/latex/amsfonts/amssymb.sty
(/usr/share/texlive/texmf-dist/tex/latex/amsfonts/amsfonts.sty))
No file purpleOZIFPY.aux.
(/usr/share/texlive/texmf-dist/tex/latex/amsfonts/umsa.fd)
(/usr/share/texlive/texmf-dist/tex/latex/amsfonts/umsb.fd) [1]
(./purpleOZIFPY.aux) )
Output written on purpleOZIFPY.dvi (1 page, 376 bytes).
Transcript written on purpleOZIFPY.log.
[1]

And this is what pidgins log said:
(14:44:30) LaTeX: Writing Message: $$test$$
(14:44:30) LaTeX: starting to analyse the message: $$test$$
(14:44:30) LaTeX: Found LaTeX-Code: test
(14:44:30) LaTeX: using '0,0,0' for foreground
(14:44:30) LaTeX: using '255,255,255' for background
(14:44:30) LaTeX: 'latex' started
(14:44:30) LaTeX: 'latex' ended normally with exitcode '0'
(14:44:30) LaTeX: 'dvipng' started
(14:44:30) LaTeX: 'dvipng' ended normally with exitcode '0'
(14:44:30) LaTeX: image creation exited with status '0'

But effectively all I get is $$test$$ instead of the desired rendering output from Latex.


text:
Q: error: ng0204: can't resolve all parameters for firestore I have some problem with testing my code.Has anyone else had this issue, and how were you able to resolve the issue. I've read the docs, and I can't get to the bottom of this issue.
I use firebase 9,
angular/fire 7.2.1,
angular 13.
My test code:
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { FriendsPageComponent } from './friends-page.component';
import { FriendsService } from './services/friends.service';

describe('FriendsPageComponent', () => {
  let component: FriendsPageComponent;
  let fixture: ComponentFixture<FriendsPageComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ FriendsPageComponent ],
      providers: [FriendsService, Firestore]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(FriendsPageComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

Error:
error properties: Object({ code: 204 })
Error: NG0204: Can't resolve all parameters for Firestore: (?).
    at getUndecoratedInjectableFactory (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:11486:1)
    at injectableDefOrInjectorDefFactory (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:11472:1)
    at providerToFactory (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:11519:1)
    at providerToRecord (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:11506:1)
    at R3Injector.processProvider (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:11402:1)
    at http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:11388:1
    at http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:4138:1
    at Array.forEach (<anonymous>)
    at deepForEach (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:4138:1)
    at R3Injector.processInjectorType (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:11388:1)


text:
Q: WMesh face shading artifacts in OpenCV I'm using OpenCV v4.4.0 with gcc v10.1 on Ubuntu 18.04.5. This code snippet:
using namespace std;
using namespace cv;
using namespace cv::viz;
......
vector<Vec3f> points{{0, 0, 0}, {1, 0, 0}, {1, 1, 0}, {0, 1, 0}, {2, 0, 0}, {2, 1, 0}};
vector<int>   faces{4, 0, 1, 2, 0, 4, 0, 2, 3, 0, 5, 1, 4, 5, 2, 1};
Viz3d         window("Mesh");
WMesh         mesh(points, faces);

window.setBackgroundColor(Color::gray());
mesh.setColor(Color::indigo());
mesh.setRenderingProperty(OPACITY, 0.4);
mesh.setRenderingProperty(SHADING, SHADING_FLAT);
mesh.setRenderingProperty(REPRESENTATION, REPRESENTATION_SURFACE);
window.showWidget("mesh", mesh);
window.spin();

creates and displays this planar mesh:

The square on the left is defined as 2 triangles and is shaded uniformly, but the square on the right, which is defined as a single quadrilateral face is not shaded uniformly. Again, the mesh is planar. Why the non-uniformity?
It becomes even more non-uniform when I change shading from SHADING_FLAT to SHADING_GOURAUD:

Can someone explain what is going on here? I know that quadrilateral faces are converted to triangles, but why the shading is non-uniform?
EDIT
As noted by Матвей Вислоух in his answer below, I intended to use:
vector<int> faces{3, 0, 1, 2, 3, 0, 2, 3, 4, 1, 4, 5, 2};

which properly defines two triangular and one quadrilateral face. This solves the problem of artifacts in the left half, but they still remain in the right half:

A: vector<int> faces{3, 0, 1, 2, 3, 0, 2, 3, 4, 1, 4, 2, 5};

There is a specific rule how opencv unpacks indices from polygon.
if there is a polygon : (5, 1, 4, 5, 2, 0) it consists of 3 triangles: (1,4,5) , (4, 5, 2), (5, 2, 0)
OLD:
vector   faces{4, 0, 1, 2, 0, 4, 0, 2, 3, 0, 5, 1, 4, 5, 2, 1};
This means you draw 3 polygons: 2 quads and 1 pentagon.
But by indices I guess that you want to draw 2 triangles, and one quad, so try this:
vector   faces{3, 0, 1, 2, 3, 0, 2, 3, 4, 1, 4, 5, 2};


text:
Q: Can I move a figure after creating it? I'm trying to create shapes with c# to my xaml application, the best way to do it would be create a shape at 0,0, draw the lines and then move the shape to its location.
Is it possible? Is it me or does not Path, PathGeometry or PathFigure have move?

A: You can move the shape to another location either by setting the location to another point by code or in xaml itself. But if u want an animation, then refer to some tutorials. I would recommend you to trial all animations using Blend.
Some link on how to do animation:
http://dotnetapp.com/blog/2012/08/26/how-to-create-simple-animation-in-your-windows-phone-app/

A: In order to move UI elements you need to either set a new margin thickness or you need to put it on a canvas and set its canvas position. If you wanted it animated do the above but put it in a timer tick event.


text:
Q: Trying to write priority queue in Java but getting "Exception in thread "main" java.lang.ClassCastException" For my data structure class, I am trying to write a program that simulates a car wash and I want to give fancy cars a higher priority than regular ones using a priority queue. The problem I am having has something to do with Java not being able to type cast "Object" as an "ArrayQueue" (a simple FIFO implementation). What am I doing wrong and how can I fix it?
public class PriorityQueue<E>
{

    private ArrayQueue<E>[] queues;
    private int highest=0;
    private int manyItems=0;

    public PriorityQueue(int h)
    {
        highest=h;
        queues = (ArrayQueue<E>[]) new Object[highest+1];   <----problem is here
    }

    public void add(E item, int priority)
    {
        queues[priority].add(item);
        manyItems++;
    }

    public boolean isEmpty( )
    {
        return (manyItems == 0);
    }

    public E remove()
    {
        E answer=null;
        int counter=0;

        do
        {
            if(!queues[highest-counter].isEmpty())
            {
                answer = queues[highest-counter].remove();
                counter=highest+1;
            }
            else
                counter++;
        }while(highest-counter>=0);

        return answer;
    }
}

EDIT
Thank you both for the quick answer to this question. I solved the problem by following your advice and one other bit of code:
public PriorityQueue(int h)
{
    highest=h;
    queues = new ArrayQueue[highest+1];
    for(int i = 0; i <= highest; i++)
    {
        queues[i] = new ArrayQueue();
    }
}

A: An Object is an Object and (in most cases) not an ArrayQueue. So indeed the cast is not possible.
Creation of generic arrays is a problem too, but in your case, this should work:
public PriorityQueue(int h)
{
    highest=h;
    queues = new ArrayQueue[highest+1];   // Gives an ignorable warning
}

EDIT
The way it is explained in your textbook is incorrect, the book needs a new revision cycle ;) The suggested cast is not allowed in Java, it's like an attempt to do
String forEverUseless = (String) new Object(); // this will not give an empty String
                                               // but an ouch-that-hurts-Exception

which is more obvious. You can never cast a class to one of its subtypes (derived classes). This is true for all classes, including arrays and generic classes.
EDIT 2
Two more suggestions:

*

*The 'add' method should get a check whether 'priority' is in the valid range of priorities, otherwise add will throw an exception (like in: queue.add(entry, -1))

*A remove method usually has an argument - you might want to call it with the element that shall be removed from the queue. (Or - if you're intention is something else, i suggest using the common queue operation names pop, push and peek)

A: The problem is almost exactly what you said -- you're making something of type Object[] and trying to cast it to ArrayQueue[], and those aren't compatible types. You should just do:
queues = new ArrayQueue[highest+1];


text:
Q: Kafka Streaming error using Pyspark I am trying to integrate Kafka and Spark. I have created a producer in Kafka
and I want to consume messages in Spark cluster.
I am using the below command for spark job submit but it is giving error.
Can you please help me with the error ?It seems I am missing some dependent jar files.
My current spark version :  2.1.1.2.6.2.0-205
Python version :  2.7.5
Python Script:
import sys

import os

from pyspark import SparkContext, SparkConf

from pyspark.streaming import StreamingContext

from pyspark.streaming.kafka import KafkaUtils

if __name__ == "__main__":

    conf = SparkConf().setMaster("local").setAppName("Spark-Kafka Integration")

    sc = SparkContext(conf = conf)

    ssc = StreamingContext(sc, 2)

    lines = KafkaUtils.createStream(ssc,'localhost:2181','raw-event-streaming-
    consumer',{'NewTopic':1})

    print(lines)

    ssc.start()

    ssc.awaitTermination()

Error logs:
 File "/usr/hdp/2.6.2.0-205/spark2/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line 319, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o37.createStream.
: java.lang.NoClassDefFoundError: org/apache/spark/Logging
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at org.apache.spark.streaming.kafka.KafkaUtils$.createStream(KafkaUtils.scala:91)
        at org.apache.spark.streaming.kafka.KafkaUtils$.createStream(KafkaUtils.scala:168)
        at org.apache.spark.streaming.kafka.KafkaUtilsPythonHelper.createStream(KafkaUtils.scala:632)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:280)
        at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
        at py4j.commands.CallCommand.execute(CallCommand.java:79)
        at py4j.GatewayConnection.run(GatewayConnection.java:214)
        at java.lang.Thread.run(Thread.java:745)


text:
Q: Is is possible for a microcontroller with a single serial output to interact with two serial peripherals? I'm looking into using Atmel's 2051 microcontroller with an Xbee and a HC-05 Bluetooth module, the micro however has only one serial connection and no possibility for expandability with memory-accessed peripherals. Is this doable or do I have to choose only one of the two?

A: Use/find/implement your own Arduino style software-serial library for slow baud-rate serial comms to one of the devices, and use the hardware UART (serial) to the other one.
You could even do software serial for BOTH bluetooth and Xbee if data rates are kept low, and you dont have any crazy hard-realtime system (higher priority control) which may cause loss of data too often.

A: Yes, You can use both. You might want to look into multiplexers. You can buy dual multiplexers. Depending on the sort of IC you use, it will normally have one input to connect your microcontroller to and two outputs. Or a long way could be to build your very own perhaps using high speed transistors or even mosfets. Although using an IC is recommended


text:
Q: 3D Movement in Processing I am making a processing sketch which uses the Oculus Rift Dk1, and the library SimpleOculusRift. Overall, what my problem is, is that I cannot seem to figure out a way to join movement and eye position on the rift. So whichever way you are looking(in the rift) is the direction you will move when you hit forward.
Currently, I have it set up so you move on a x and z axis. ( Using translate() and the up down left and right arrow keys. )
I used this code from the library's example to get the numbers I need which show the direction I am looking at.
 PMatrix3D headOrientationMatrix = oculusRiftDev.headOrientationMatrix();
  headOrientationMatrix.translate( 50, 0, -10 );

  PVector eyePos = new PVector(0, 0, 0);
  PVector dir = headOrientationMatrix.mult(eyePos, null);

When I add println(dir); I get a pair of 3 numbers looking something like this:
[ 1.7912731, -11.410956, -49.66469 ]
[ 1.7770205, -13.271997, -49.20057 ]
[ 2.1940613, -14.491295, -48.838394 ]
[ 2.7236567, -14.90203, -48.687893 ]
[ 3.203349, -14.766355, -48.700035 ]
[ 3.7733526, -14.435215, -48.758453 ]
[ 4.232833, -13.569878, -48.96878 ]
[ 4.137532, -13.105787, -49.103153 ]
[ 4.211087, -12.630456, -49.22132 ]
[ 4.1642704, -11.712718, -49.451702 ]
[ 3.9711514, -10.351211, -49.770298 ]
[ 6.6861124, -7.4438334, -49.998856 ]
[ 7.1228933, -7.5860662, -49.917095 ]

If I am looking straight ahead I get something similar to 50,0,0 and behind me I get -50,0,0. When I look to my right, I get 0,0,50, and to my left 0,0,-50. Everything else is just numbers in between that are constantly updating.
For grid movement, in a simplified definition - I am using multiple PVectors which add a small number when you hit a up or down or left or right arrow key, which gives me movement.
Here is the code for my movement on the grid:
void moveX() {
  //movement for x axis
  if (keyPressed == true) {
    if (key == CODED) {

      if (keyCode == LEFT) {
        walk.x += 1;
      }
      if (keyCode == RIGHT) {
        walk.x -= 1;
      }
    }
  }
  if(keyPressed == false){
    walk.x = 0;
  }
}

void moveZ() {
  //movement for z axis
  if (keyPressed == true) {
    if (key == CODED) {
      if (keyCode == DOWN) {
        walk.z -= .5;
      }
      if (keyCode == UP) {
        walk.z += .5;
      }
    }
  }

  if(keyPressed == false){
    walk.z = 0;

  }
}

I then add the PVector walk, to the PVector spawn. The spawn PVector are the 3 'spawn' points for the sketch when you start. The walk PVector simply adds a number (or force) to make it move.
translate( spawn.x, spawn.y, spawn.z);

In conclusion, I just can't seem to figure out how to move forward in the direction I am looking towards using the Oculus Head Set. Hope this was clear enough. Thank you in advance to anyone that could maybe solve this problem that I have been picking at all day.
Since I cannot post a photo of my sketch, its basically a 3D grid box that you can move around in, within processing.

A: As far as I understood, you would like to move forward always in direction, which the user look.
Using vectors is the first step. You add the value of the vectors with .add. So basically for every frame: New Location = Location + the applied velocity to the current location. Assuming location vector and velocity
location.add(velocity)

Since you will be adding 'velocity' in draw/update, you will need to set up some limit on the acceleration, in contrast of pressing a button where the limit is number of clicks.
About the 3D, if you mean forward as in going towards the depth of the screen (as in computer games) that would be -Z in processing. Check out the 3D transformations if needed.
From your code I can see that you are having already PVector dir. However you will need a location vector as well and to subtract the input with the location, instead of multiplying. Than you will probably need to normalize() the direction, add the velocity and the changes finally to the location:
  PVector eyePos = new PVector(0, 0, 0);
  PVector location = new PVector(0, 0, 0);
  PVector dirOculus = headOrientationMatrix.mult(eyePos, null); //Double check, why you need to mult by null vector.
  PVector dir = PVector.sub(dirOculus, location);

  dir.normalize();
  acceleration = dir;
  velocity.add(acceleration);
  location.add(velocity);
  ----

I hope you got the idea and can put it yourself in context.


text:
Q: Guessing game in C with while loops and if statements debugging So I'm creating a program that's a guessing game. It's supposed to ask player 1 to enter a number between 0 and 99, if they enter anything outside of that the code should ask them to retry this.
Then it will ask for a number of guesses/attempts Player 2 has to enter what they think the number is. If it's too high the program will say so, if it's too low the program will say so. If it's just right- Player 2 wins and if they run out of guesses the program is to say that too.
My problem is with the second half of this code. Where I'm trying to fit in the number of guesses with the remaining guesses. The loop isn't working; here's the code:
  int secretnumber;
  int guesses;
  int secretnumberguess;
  int remainingguesses;

  while (1)  {
    printf("Player 1: Type a number between 0 and 99 and press return:\n");
    scanf(" %d",&secretnumber);

    if (secretnumber > 99 || secretnumber < 0) {
      printf("Secret number cannot be greater than 99 or below 0.\n");
      continue;
    }
    break;
  }

  printf( "Type the number of guesses that player 2 gets and press return: \n");
  scanf("%d",&guesses);

  remainingguesses = guesses - 1;

  while (remainingguesses != 0)  {
    printf("Player 2: Type your guess and press return (guesses remaining:%d):\n",&remainingguesses);
    scanf(" %d",&secretnumberguess);

    if (secretnumberguess > secretnumber) {
      printf("Your guess was greater than the secret number.\n");

      else if (secretnumberguess < secretnumber)
        printf("Your guess was less than the secret number.\n");

        else (secretnumberguess == secretnumber)
               printf("Your guess was equal to the secret number. You win!\n");
      continue;
    }
    break;
  }

  if (remainingguesses == 0)
    printf("Sorry you are out of guesses. You lose.\n");

I'm entirely new to this and trying to debug and fix my code. But loops are truly a nightmare for me especially when you throw if statements into the mix. I realize I'm very incompetent and I apologize but could someone help me as I'm totally confused on the second half of my code.

A: First off, this code:
while (remainingguesses != 0)  {
    printf("Player 2: Type your guess and press return (guesses remaining:%d):\n",&remainingguesses);
    scanf(" %d",&secretnumberguess);

is wrong. When using the printf statement and you are trying to input the variable in the statement, you don't need to put & in it.
So you need to change you code to:
while (remainingguesses != 0)  {
    printf("Player 2: Type your guess and press return (guesses remaining:%d):\n",remainingguesses);
    scanf(" %d",&secretnumberguess);

You need to remove & in the printf statement. We only use & like to store something into a variable.

A: Write code step by step, respecting proper syntax and understanding what you want to accomplish next. Don't rush. It just takes time to learn and programming is no different.
remainingguesses = guesses - 1;

The variable remainingguesses controls your loop, but you only assign a value to it once and never change it afterwards. The loop will then never end. After correcting this, ask yourself: How many guesses will I be able to do if I enter 3 guesses?
printf("Player 2: Type your guess and press return (guesses remaining:%d):\n",&remainingguesses);

Here you are printing the memory address that holds the value remainingguesses, not its actual value. This is the concept behind pointers, which I advise you to research in order to get a proper understanding of the mechanics involved here.
if (secretnumberguess > secretnumber) {
  printf("Your guess was greater than the secret number.\n");

  else if (secretnumberguess < secretnumber)
    printf("Your guess was less than the secret number.\n");

    else (secretnumberguess == secretnumber)
           printf("Your guess was equal to the secret number. You win!\n");
  continue;
}
break;

Careful with those braces! The entire block will be entered only if the guess is bigger than the secretnumber. In any other case, execution will just jump to the break and then exit the while loop. I believe this mixup caused you to confuse the usage of continue and break, too.
Else acts as a contingency for your conditional statements. It doesn't need a boolean value nor a comparison like the one you're using. In other words, if the guessed number is neither bigger nor smaller than the secret one, it's guaranteed to be equal to it.
This has been mentioned already but I can't stress it enough: Pay attention to the compiler. Research every error and warning it provides you. You will make sure progress this way.


text:
Q: How to connect to MongoDB 3.2 in Java with username and password? I'm using MongoDB 3.2 in my application. The code below demonstrates database initialization logic:
private void dbInit(String dbName) {

    String mongoClientURI = "mongodb://" + DB_URL + ":" + DB_PORT;
    MongoClientURI connectionString = new MongoClientURI(mongoClientURI);

    // enable SSL connection
    MongoClientOptions.builder().sslEnabled(true).build();

    if (this.mongoClient == null) {
        this.mongoClient = new MongoClient(connectionString);
    }

    // create database if doesn't exist
    this.mongoClient.getDatabase(dbName);
}

This code works fine, now I want to introduce access level separation to database.
The steps to do that:

*

*Define users:

use myAppDB
db.createUser(
   {
      "user": "myAdmin",
      "pwd": "123090d1487dd4ab7",
      roles: [ "readWrite", "dbAdmin" ]
   }
)

use myAppDB
db.createUser(
   {
      "user": "guest",
      "pwd": "guest",
      roles: [ "read" ]
   }
)

*Re-create the MongoDB 3.2 service in authentication mode:
"C:\Program Files\MongoDB\Server\3.2\bin\mongod.exe" --install --dbpath=C:\data\db --logpath=C:\data\log\log.txt --auth --service. And run it.

*Change the mongoClientURI connection string to
String mongoClientURI = "mongodb://" + DB_SRV_USR + ":" + DB_SRV_PWD + "@" + DB_URL + ":" + DB_PORT;

where DB_SRV_USR = myAdmin and DB_SRV_PWD = 123090d1487dd4ab7.

*Check the authenticated connection in IDEA's Mongo Explorer with the same credentials, everything is OK.

*Execute my application and get exception Authentication failed.
My questions:

*

*How to connect to MongoDB 3.2 in Java with username and password? I saw a couple of examples but they are using deprecated methods.

*Should I add my users to myAppDB or to admin table? In some tutorials I saw that users are created in admin table is it a good idea or it worth to create users only in a database they are going to work with?

A: Tested with mongodb-3.4.2 and mongo-java-driver-3.4.2.jar
(1) Use MongoCredential
MongoCredential credential = MongoCredential.createCredential("user", "database", "passwd".toCharArray());
MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017), Arrays.asList(credential));
MongoDatabase db = mongoClient.getDatabase( "test" );
MongoCollection collection = db.getCollection("mycol");
FindIterable fi = collection.find();
MongoCursor cursor = fi.iterator();

(2) Use MongoClientURI
MongoClientURI uri = new MongoClientURI("mongodb://user:passwd@localhost:27017/?authSource=test");
MongoClient mongoClient = new MongoClient(uri);

There are some variant forms for using MongoCredential and MongoClientURI for different authentication mechanisms, check here for details

A: As MarkusWMahlberg correctly noted, it is necessary to note the database name in the connection string.
For instance:
String mongoClientURI = "mongodb://" + DB_SRV_USR + ":" + DB_SRV_PWD + "@" + DB_URL + ":" + DB_PORT + "/" + dbName;


text:
Q: Autoclose dropdown menu problem with ng-select I'm trying to create a dropdown menu, that closes automatically when the user click outside of it. In this menu I added a ng-select component, but when I click on one of the options, the menu will close, because the dropdown panel of the ng-select is not inside the DOM when it is closed, is there any way to achieve what I want? The dropdown menu to not close when the user select a ng-option?
Here there is an example of the problem:
https://stackblitz.com/edit/angular-8m1ta5?file=src%2Fapp%2Fapp.component.ts
Here is the code that I use to keep track of the click of the user:
  @ViewChild('father', {static: false}) father;
  @HostListener('document:click', ['$event.target'])
  public onClick(targetElement) {
    const clickedInside = this.father.nativeElement.contains(targetElement);
    if (!clickedInside) {
      this.dropdown = false;
    }
  }

#father identify the container of the dropdown menu.

A: The Attribute [closeOnSelect]="false" should do the work. You will have to add it to the <ng-select> tag
So, from the stackblitz the code will become:
<ng-select placeholder="Status" [closeOnSelect]="false">
        <ng-option [value]="'0'">Option 1</ng-option>
        <ng-option [value]="'1'">Option 2</ng-option>
        <ng-option [value]="'2'">Option 3</ng-option>
</ng-select>

Here you can find the documentation https://github.com/ng-select/ng-select

A: binding the isOpen property of ng-select to your components dropdown flag should do the trick:
<ng-select placeholder="Status" [isOpen]="dropdown">
    <ng-option [value]="'0'">Option 1</ng-option>
    <ng-option [value]="'1'">Option 2</ng-option>
    <ng-option [value]="'2'">Option 3</ng-option>
</ng-select>

component.ts
export class AppComponent  {
  dropdown = false;

  @ViewChild('father', {static: false}) father;
  @HostListener('document:click', ['$event'])
  public onClick(e) {
    const clickedInside = this.father.nativeElement.contains(e.target);
    if (!clickedInside) {
      this.dropdown = false;
    }else{
      this.dropdown=true;
    }
  }
}

have a look at https://github.com/ng-select/ng-select#inputs
I have altered your stackblitz


text:
Q: SwiftUI view local PDF using PDFkit I want to view pdf in my app I tried many ways but I don't know why I always get error.
import SwiftUI
import PDFKit

struct PDFKitView: View {
    var url: URL
    var body: some View {
        PDFKitRepresentedView(url)
    }
}

struct PDFKitRepresentedView: UIViewRepresentable {
    let url: URL
    init(_ url: URL) {
        self.url = url
    }

func makeUIView(context: UIViewRepresentableContext<PDFKitRepresentedView>) -> PDFKitRepresentedView.UIViewType {
    let pdfView = PDFView()
    pdfView.document = PDFDocument(url: self.url)
    pdfView.autoScales = true
    return pdfView
}

func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PDFKitRepresentedView>) {
    // Update the view.
}
}

I used this pdfkit way from google but still I get error
@State var pdfURL:URL?

ForEach(userPattern.filePath, id: \.self) {users in

 let fileUrl = URL(fileURLWithPath: users)
 let fileName = fileUrl.lastPathComponent.replacingOccurrences(of: ".pdf", with: "")

  pdfUI(fileName: fileName)
    .padding([.leading, .bottom, .trailing])
    .onTapGesture {

          namePDF = fileName
           pdfURL = fileUrl
           self.viewLocalPDF = true
                            }

   }.sheet(isPresented: $viewLocalPDF) {
       PDFKitView(url: pdfURL)
 }

So when I click on file the app crashes and I get this error "Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value"
can you please help me why isn't working to view the local pdf file ?
UPDATE: The error is at PDFkitView(url: pdfURL!) and I tried to use all safe unwrapping (guard , if let) but it's the same thing it responed with nil value, I even insert ready value I thought it maybe from the loop the issue like this :
PDFKitView(url: URL(string: "file:///private/var/mobile/Library/Mobile%20Documents/com~apple~CloudDocs/Downloads/MaherNew.pdf"))

but it open only white sheet ?


text:
Q: What to do with excess Culture? (BNW)Granted, I understand it's exceptionally difficult to adopt every social policy and ideological tenant before achieving any other victory condition... but I actually managed to do it by accident and kept a game running solely for meta-purposes. Technically speaking, one could force a world ideology through the world congress and adopt all new tenants for both of the ideologies they didn't choose, but even after that, there appears to be no recurring way of spending amassed culture, unless I've overlooked something completely and would feel like a total moron

A: As far as I know, there's nothing to do with excess culture.  In Brave New World, at least, having massive Culture reserves would prevent a cultural victory by some other Civ, but there's no other use for it.

A: Prior to BNW, once I had got too much culture I would jump from the Autocracy / Order / Freedom trees.


text:
Q: Read N last lines of a large shared file with NodeJs I have two codes one for reading shared file using smb2:
// load the library
var SMB2 = require('smb2');

// create an SMB2 instance
var smb2Client = new SMB2({
  share:'\\\\192.168.0.111\\folder'
, domain:'WORKGROUP'
, username:'username'
, password:'password'
});

// read the file
smb2Client.readFile('path\\to\\the\\file.txt', "utf-8", function(error, data){
    if(error) throw error;
    console.log(data);
});

And the other one for reading the last 20 lines of a local file using read-last-line:
// load the library
const readLastLine = require('read-last-line');

// read the file
readLastLine.read('path\\to\\the\\file.txt', 20).then(function (lines) {
    console.log(lines)
}).catch(function (err) {
    console.log(err.message);
});

I didn't know how to combine the two of them.
Do you have any suggestions.
Thanks.

A: If smb2 and read-last-line both supported streams, it would be easy. According to their documentation at least, neither does, but pv-node-smb2 has a method createReadStream.
Here is a stream transformer that processes its input line by line, but keeps only the most recent n lines and outputs them at the end. This avoids keeping huge files entirely in memory:
class Tail extends stream.Transform {
  constructor(n) {
    super();
    this.input = new stream.PassThrough();
    this.tail = [];
    readline.createInterface({input: this.input, crlfDelay: Infinity})
    .on("line", function(line) {
      if (this.tail.length === n) this.tail.shift();
      this.tail.push(line);
    }.bind(this));
  }
  _transform(chunk, encoding, callback) {
    this.input.write(chunk);
    callback();
  }
  _flush(callback) {
    callback(null, this.tail.join("\n"));
  }
}

(Likely, there is already an NPM package for that.)
Now you can pipe the SMB2 read stream through that transformer:
new require("pv-node-smb2").PvNodeSmb2(...).createReadStream(...)
.pipe(new Tail(20))
.pipe(process.stdout);

A: I couldn't install pv-node-smb2 package, it gave me too much errors so I tried a Powershell command that works like the tail command in Linux
Get-Content \\192.168.0.111\path\to\the\file.txt -Tail 20

Which returns the last 20 lines of the file and then run that script in NodeJs
let last20lines = "";
let spawn = require("child_process").spawn,child;
child = spawn("powershell.exe",["c:\\wamp64\\www\\powershell_script.ps1"]);
child.stdout.on("data",function(data){
   last20lines += data
});
child.stdin.end();


text:
Q: Intersection of Span of Vectors and Hypercube Consider a set of vectors $\{v_1,\ldots,v_k\}\in\mathbb{R}^n$. Denote the span of these vectors by $Sp(v_1,\ldots,v_k)$. Is there a method to determine,
$Sp(v_1,\ldots,v_k)\cap \{0,1\}^n$
That is, the intersection of the span of the vectors and the $n$-hypercube?
Some thoughts: If the set of vectors is linear independent then every $u\in Sp(v_1,\ldots,v_k)$ can be expressed as $u=\sum_i a_iv_i$ for some real numbers $a_i$. If we try to solve for $a_i$ such that $u=e_j$ where $e_j$ is the $j$-th unit vector, we may find a solution. The it follows that $e_j\in Sp(v_1,\ldots,v_k) \cap \{0,1\}^n$. If $e_{j_1}$ and $e_{j_2}$ are both in the span, then their sum is in the span as well (simply sum the respective $a_i$ terms). Ultimately, we arrive at the set of all unit vectors in the span. Then all combinations of these will give all points on the hypercube.
Is this reasoning valid? Is there an easier way?

A: You didn't mention whether you wanted computational efficiency or not, so I'm going to start by assuming "not".
In that case, you can do the following:
Extend $v_1, \ldots, v_k$ by $e_1, \ldots, e_n$ to get an ordered list of $n+k$ vectors that certainly spans $n$-space (because the last $n$ do!).
Now apply Gram-Schmidt to those, with the rule that whenever you get a $0$-vector, you simply ignore it. For instance, if $v_1 = e_2, v_2 = e_2+e_1$, then your initial set would be
$$
e_2, e_2+e_1, e_1, e_2 e_3
$$
and Gram-Schmidt, one step at a time, would produce
$$
e_2 \\
e_2, e_1 \\
e_2, e_1, 0 [which~we~delete] \\
e_2, e_1, [0], [0] \\
e_2, e_1, [0], [0], e_3
$$
where the brackets indicate elements that were computed and then thrown out.
When you're done, you end up with a list of orthogonal vectors
$$
u_1, u_2, \ldots, u_p, w_1, w_2, \ldots, w_{n-p}
$$
with the property that the span of the $u$s is the same as the span of the $v$s, while the $w$s span the orthogonal complement of the $v$s.
Form a matrix
$$
W = \begin{bmatrix}
w_1 & w_2 & \ldots & w_{n-p}
\end{bmatrix}
$$
whose columns are the $w$ vectors, and for each vertex $P_i$ of the $n$-cube, compute
$$
t_i = wP_i.
$$
This is the projection of $P_i$ onto the orthog complement of span{$v_1, \ldots, v_k$}, in $w$-coordinates. If $t_i$ is zero, then $P_i$ is in the span of the original $v$s; if it's nonzero, then it's not in the span.
As written, you have to do this for all $2^n$ points, which is slow. But as you observe, once you find $r$ vectors in the span, all $2^r$ other vectors that are formed as positive sums of those will also be in the span, so there should be some way to simplify a bit.
I suspect that if you put the vectors $t_i$ into a matrix $T$ (where rather than using every vertex $P_i$ of the $n$-cube, you just just $e_1, \ldots, e_n$), you can apply Gaussian elimination to the columns of $T$, and can eventually use this to find a spanning set of vertices that are in the subspace $V$. For instance, if $t_1 = Me_1$ and $t_2 = Me_2$ are both nonzero, but happen to be negatives of one another, then $M(e_1 + e_1)$ will be in $V$. And I just realized that the matrix $T$ I've just described is really just the original matrix $M$. I'll also observe that since you only want POSITIVE linear combinations of things, straight Gaussian elimination won't suffice...but something a lot like it might well do.
I grant this isn't a complete solution, but I hope it's a useful start.